Click here to Skip to main content
15,887,350 members
Please Sign up or sign in to vote.
1.00/5 (4 votes)
See more:
I am loading a combo Box with staff ids from a sql db but am not getting it right.
This is what I did:
i really dont know how to do that, i made a research and tried my hands on it but didnot worked. pls how do i load only
staff id into a combo box
public void loadID()
        {
            SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
            conn.ConnectionString = "Data Source=MICKY-PC;Initial Catalog=SMS;User ID=sa;Password=mike";
            conn.Open();

            SqlCommand cmd = new SqlCommand();
            string sqlQuery = null;
            sqlQuery = "select * from tblstaffpersonaldetails";

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

            SqlDataReader dr = null;

            dr = cmd.ExecuteReader();

            this.cboStaffid5.Items.Clear();
            while (dr.Read())
            {
                this.cboStaffid5.Items.Add(dr["staffid"]);
            }
            conn.Close();        
        }

        private void cboStaffid5_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadID();
        }
Posted
Updated 29-May-12 11:37am
v3
Comments
R. Giskard Reventlov 29-May-12 15:39pm    
So what's your question?
mikeoabban 30-May-12 4:12am    
how do i load only staff id into a combo box cbostaffid5 after i have created
the loadID method
Sergey Alexandrovich Kryukov 29-May-12 15:43pm    
So what? Loading a combo box with values? Would be strange if you loaded it without values... :-)
"Not getting it right" is not informative...
--SA
mikeoabban 30-May-12 4:10am    
how do i load only staff id into a combo box cbostaffid5 after i have created
the loadID method
Sergey Alexandrovich Kryukov 29-May-12 15:45pm    
Are you sure you really want to select ALL from a table? Why would you ever need it?
--SA

Ok the following code should work fine. but there are some queries
1. Why are you populating the combo box on selected index change on the same object?
2. You also need to call the LoadID() method to get the data first otherwise the selected index method wont invoke.


edit: The code snippets on here don't support the method XML comments(///) so i have added them as basic comments
C#
// Populates the combo box with the staffID from the database
private void LoadID()
{
    System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection("Data Source=MICKY-PC;Initial Catalog=SMS;User ID=sa;Password=mike");
    connection.Open();
    System.Data.SqlClient.SqlCommand command = connection.CreateCommand();
    command.CommandText = "select staffid from tblstaffpersonaldetails";
    command.CommandType = CommandType.StoredProcedure;
    System.Data.SqlClient.SqlDataReader reader = null;


    cboStaffid5.Items.Clear();

    try
    {
        reader = command.ExecuteReader();

        if (!reader.HasRows)
        {
            MessageBox.Show("No records to add");
            return;
        }

        while (reader.Read())
        {
            if (!reader["staffid"].Equals(DBNull.Value))
            {
                cboStaffid5.Items.Add(reader["staffid"].ToString());
            }
        }
        MessageBox.Show("Import Completed Successfully Woot!!!");
    }
    catch (Exception ex)
    {
        // shows error message obv
        MessageBox.Show("Error: " + ex.Message);
    }
    finally
    {
        // this is to ensure that the reader and connection are closed properly (even on errors)
        if (reader != null)
        {
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            reader = null;
        }
        if (connection.State != ConnectionState.Closed)
        {
            connection.Close();
        }
    }
}

//reloads the data from the database upon selection change (not sure why this is done)
private void cboStaffID_SelectedIndexChanged(object sender, EventArgs e)
{
    int currentSelectedIndex = (sender as ComboBox).SelectedIndex;
    LoadID();
    (sender as ComboBox).SelectedIndex = currentSelectedIndex;
}


And for those who prefer OleDB, just change the SQLClient Objects in the LoadID method to the following
C#
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection("Data Source=MICKY-PC;Initial Catalog=SMS;User ID=sa;Password=mike");
connection.Open();

System.Data.OleDb.OleDbCommand command = connection.CreateCommand();
command.CommandText = "select * from tblstaffpersonaldetails";
command.CommandType = CommandType.StoredProcedure;
System.Data.OleDb.OleDbDataReader reader = null;
 
Share this answer
 
v2
only just use instead oledb use SqlClient
C#
try
{
   OleDbConnection con = new OleDbConnection("Provider= Microsoft.Jet.OLEDB.4.0;Data Source=D:\\EID.mdb");
   string str = "select * from membersamount";
   con.Open();
   OleDbCommand cmd = new OleDbCommand(str, con);
   OleDbDataReader dr = cmd.ExecuteReader();
   while (dr.Read())
   {
      comboBox3.Items.Add(dr[6]);
   }
   dr.Close();
}
catch (Exception es)
{
   MessageBox.Show(es.Message);
}
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 29-May-12 15:44pm    
Why? SqlClient is deprecated by Microsoft as of v.4.0, if I'm not much mistaken, OleDb is recommended.
--SA
this is for sql db your Q for sql db
C#
con = new SqlConnection(GlobalClass.conn);
con.Open();
string sql = "SELECT EmpID FROM EmployeeSalaryAgreement WHERE EmpID NOT IN('HR001')";
SqlCommand1 = new SqlCommand(sql, con);
SqlDataReader dr = SqlCommand1.ExecuteReader();
while (dr.Read())
{
   cmbEmpID.Items.Add(dr[0]);
   count++;
}
dr.Close();
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900