I want to insert each row in SQL into combobox, where EmployeeID will be combobox Value, and EmployeeFirstName EmployeeLastName will be text of combobox item. However this line<
First, use Add to add items to the ComboBox. Second, I prefer anonymous type to fill the ComboBox while you use plain native Sql and simple DataReader immediately inside your form.
void comboboxrefresh()
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT EmployeeID,EmployeeFirstName,EmployeeLastName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
combobox1.ValueMember = "Id";
combobox1.DisplayMember = "FullName";
while (dr.Read())
{
comboBox1.Items.Add(
new {
FullName = dr.GetString(1) + " " + dr.GetString(2),
Id = dr.GetInt32(0)
});
}
}
cnn.Close();
}
Update:
I noticed that naively adding to the Item list is not working! Instead, DataSource property of ComboBox should be set to desired list. So the working code is as:
var list = new List