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
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)
{
MessageBox.Show("Error: " + ex.Message);
}
finally
{
if (reader != null)
{
if (!reader.IsClosed)
{
reader.Close();
}
reader = null;
}
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
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
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;