Hi ,
I am using C# to do my projects and I have connected to a MS SQL database file and I am using MS visual studio 2008 standard edition. I need to get all the users first name and the last name and display in a combo box when the windows form loads. but the user who logins his name should appear in the top of the combo box. how can i do this?
Please can someone give me a solution.

Thank You!!

There's many ways to handle such a situation. Probably when a user log in you connect to the database to check his/her data. In that moment you can just add to the combobox his/her first name, last name and remember in variable his/her UserID (so the field which uniquely identify users). Then you can use a method like below:

private void FillComboBox(string connectionString, string loggedUserID)
        {
            string query = "select UserID, FirstName, LastName from DaniWeb.dbo.Users;";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(query, connection);
                connection.Open();
                SqlDataReader sqlReader = command.ExecuteReader();
                try
                {
                    while (sqlReader.Read())
                    {
                        if (sqlReader[0].ToString() != loggedUserID)
                            comboBox2.Items.Add(sqlReader[1] + " " + sqlReader[2]);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    sqlReader.Close();
                }
            }
        }

There's many ways to handle such a situation. Probably when a user log in you connect to the database to check his/her data. In that moment you can just add to the combobox his/her first name, last name and remember in variable his/her UserID (so the field which uniquely identify users). Then you can use a method like below:

private void FillComboBox(string connectionString, string loggedUserID)
        {
            string query = "select UserID, FirstName, LastName from DaniWeb.dbo.Users;";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(query, connection);
                connection.Open();
                SqlDataReader sqlReader = command.ExecuteReader();
                try
                {
                    while (sqlReader.Read())
                    {
                        if (sqlReader[0].ToString() != loggedUserID)
                            comboBox2.Items.Add(sqlReader[1] + " " + sqlReader[2]);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    sqlReader.Close();
                }
            }
        }

hey thank you for the code but when i do it there is an syntax error in line 7 with command highlighted in red
what is wrong here :(the code i wrote is below)

String connectionsrting = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\awaduge\My Documents\Visual Studio 2008\Projects\Administrative Database\Administrative Database\AdminDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";

        User u = new User();
        DB db = new DB();

private void FillComboBox(String connectionsrting)
        {
            String query = @"Select * From Employee;";
            using(SqlConnection connection = new SqlConnection(connectionsrting)
            {
                SqlCommand command = new SqlCommand(query,connection);
                db.openConnection();
                SqlDataReader sqlReader = command.ExecuteReader();

                try 
                {
                    while (sqlReader.Read())
                    {
                        if (sqlReader[0].ToString() != u.getUName())
                            cmbPM.Items.Add(sqlReader[1] + " " + sqlReader[2]);
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                        sqlReader.Close();
                }
            db.closeConnection();
            }
        
        }

No line is highlighted... so I am not sure if you refer to the code proposed by me or to your modified version... But:
1. there's many ways to connect to the database but you have to choose one in any case and stick to it... so you open the connection using your own class:

DB db = new DB();
db.openConnection();
db.closeConnection();

or you do that in the way I proposed

using (SqlConnection connection = new SqlConnection(connectionString)) {}

or choose another possibility to do that but simply decide to something...
2. If you ask a question add all the information that can be useful to find the solution - in that case, as you mentioned that an error occurred, you could copy and paste the message...
if you referred to your version of the code certainly you are missing the closing bracket ")" in the end of the line... you typed:

using(SqlConnection connection = new SqlConnection(connectionsrting)

it should be:

#
using (SqlConnection connection = new SqlConnection(connectionString))

3. You do NOT have to close the connection to the database in the above example (at least if you will decide to stick to my version). As the connection is open in the using statement outside of the defined scope it will be disposed... (refer to MSDN documentation of using statement)...
4. I guess there's more errors in your code snippet but it is a little bit hard to process - correct it using above hints and post a new version...

hey sorry about that, i copied your code and an error occurred in using (SqlConnection connection = new SqlConnection(connectionString)) line highlighting the word connection. Also can you please explain to me the following the you have quoted in your code. Shown below

"
#
while (sqlReader.Read())
#
{
#
if (sqlReader[0].ToString() != loggedUserID)
#
comboBox2.Items.Add(sqlReader[1] + " " + sqlReader[2]);
#
}

"

thank You

hi i have diffrent excel sheet data i just want to show and read in combo box after i select value this value add in list box so please help me

i have a c# form which contains textbox, combobox, and radio buttons, i am able to save data
from the form to my database. but am having problems rerieving data from the sql database
onto my combobox and radio buttons. the data is not displaying in the combobox and
radio button is always returning Male

codes in my class

public bool searchpersonDetails(string personid, string personname)
        {

            SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
            conn.ConnectionString = "Data Source=pc101;Initial Catalog=REMITTANCE;User ID=sa;Password=mike";
            conn.Open();



            if (client_id != null)
            {

                Fom1 frm = new Fom1(personname);
                frm.ShowDialog();

            }



                SqlCommand cmd = new SqlCommand();
                string sqlQuery = null;
                sqlQuery = "select *,floor(datediff(getdate(),date_ofbirth)/365) AS AGE from tblspersonaldetails where client_id='" + personid + "'";

                sqlQuery = "select * from tblspersonaldetails where client_id='" + personid + "'";

                cmd.Connection = conn;
                cmd.CommandText = sqlQuery;
                cmd.CommandType = System.Data.CommandType.Text;

                SqlDataReader dr = null;
                dr = cmd.ExecuteReader();


                if (dr.Read())
                {
                    frmPersonal person = new frmPersonal();

                    client_id = dr["client_id"].ToString();
                    surname = dr["surname"].ToString();
                    othername = dr["othername"].ToString();
                    gender = dr["gender"].ToString();
                    date_ofbirth = (DateTime)dr["date_ofbirth"];
                    nationality = dr["nationality"].ToString();
                    age = dr["age"].ToString();
                    residential_address = dr["residential_address"].ToString();
                    postal_address = dr["postal_address"].ToString();
                    contact_number = dr["contact_number"].ToString();
                    marital_status = dr["marital_status"].ToString();
                    spouse_name = dr["spouse_name"].ToString();
                    email = dr["email"].ToString();
                    occupation = dr["occupation"].ToString();
                    typeof_id = dr["typeof_id"].ToString();

                    id_number = dr["id_number"].ToString();
                    id_expirydate = (DateTime)dr["id_expirydate"];
                    remarks = dr["remarks"].ToString();
                    picture = dr["picture"].ToString();
                    return true;
                    //cmd.CommandText = null;
                }



            else
            {
                return false;
            }

                conn.Close();             

    }

codes behind the form is

private void lklSearch_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {

            SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
            conn.ConnectionString = "Data Source=pc101;Initial Catalog=REMITTANCE;User ID=sa;Password=mike";
            conn.Open();


            try
            {
                Personal person = new Personal();
                Remittances Remitt = new Remittances();

                if (person.searchpersonDetails(txtClientid.Text, txtSurname.Text))
                {
                    var 
                    _with3 = this;
                    _with3.txtClientid.Text = person.ID.ToString();
                    _with3.txtSurname.Text = person.Sname.ToString();
                    _with3.txtOthername.Text = person.Oname.ToString();

                    if (person.sex.ToString() == "Female")
                    {
                        optFemale.Checked = true;
                        optMale.Checked = false;
                    }
                    else 
                    {
                        optMale.Checked = true;
                        optFemale.Checked = false;
                    }



                    _with3.dtpDob.Value = person.BirthDate;
                    _with3.txtNationality.Text = person.country.ToString();
                    _with3.txtResidentialaddress.Text = person.addressResidential.ToString();
                    _with3.txtPostaladdress.Text = person.AddressPostal.ToString();
                    _with3.txtContactnumber.Text = person.NumberContact.ToString();


                    string mstatus = person.statusMarital.ToString();
                    switch (mstatus)
                    {
                        case "Single":
                            this.cboMaritalstatus.Text = "Single";
                            break;
                        case "Married":
                            _with3.cboMaritalstatus.Text = "Married";
                            break;
                        case "Widow(er)":
                            _with3.cboMaritalstatus.Text = "Widow(er)";
                            break;
                        case "Divorce":
                            _with3.cboMaritalstatus.Text = "Divorce";
                            break;
                    }


                    _with3.txtSpousename.Text = person.nameSpouse.ToString();
                    _with3.txtEmail.Text = person.mail.ToString();
                    _with3.txtOccupation.Text = person.Work.ToString();

                    string iType = person.idtype.ToString();
                    switch (iType)
                    {
                        case "Bank ID Card":
                            this.cboIdtype.Text = "Bank ID Card";
                            break;
                        case "Driver Licence":
                            _with3.cboIdtype.Text = "Driver Licence";
                            break;
                        case "Passport":
                            _with3.cboIdtype.Text = "Passport";
                            break;
                        case "National Identification":
                            _with3.cboIdtype.Text = "National Identification";
                            break;
                        case "NHIS":
                            _with3.cboIdtype.Text = "NHIS";
                            break;
                        case "SSNIT":
                            _with3.cboIdtype.Text = "SSNIT";
                            break;
                        case "Voters ID":
                            _with3.cboIdtype.Text = "Voters ID";
                            break;
                    }

                    _with3.txtIdnumber.Text = person.numberID.ToString();
                    _with3.dtpExpiringdate.Value = person.expirydateID;
                    _with3.txtRemarks.Text = person.myremarks.ToString();


                else
                {
                    MessageBox.Show("Remittance Details Record not found");
                }

                }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                //return new SqlCommand();
            }

            finally
            {
                // Close data reader object and database connection


                if (conn.State == ConnectionState.Open)
                    conn.Close();
            }

        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.