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<
Try this
comboBox1.Items.Insert(index, dr.GetString(1) + dr.GetString(2));
Where index
is an integer value where you want to insert in combobox
Did you mean this
comboBox1.Items.Insert(dr.GetInt32(0), dr.GetString(1) + dr.GetString(2));
If you want to just add in combobox try the following
comboBox1.Items.Add(dr.GetString(1) + dr.GetString(2));
I think you're looking for DataSource
void comboboxrefresh()
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT EmployeeID, (EmployeeFirstName + EmployeeLastName) as EmployeeName FROM Employees", cnn);
DataTable table = new Datatable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(table);
comboBox1.DisplayMember = "EmployeeName";
comboBox1.ValueMember = "EmployeeID";
comboBox1.DataSource = table;
cnn.Close();
}
Define a new class
public class EmpItem
{
public int empID;
public string empName;
}
While reading the DataReader create an instance of this class and add it to the combobox items collections. Do not forget to set the DisplayMember and ValueMember of the combobox
void comboboxrefresh()
{
comboBox1.DisplayMember = "empName";
comboBox1.ValueMember = "empID";
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT EmployeeID,EmployeeFirstName,EmployeeLastName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
EmpItem ei = new EmpItem() { empID=dr.GetInt32(0), empName = dr.GetString(1) + dr.GetString(2)};
comboBox1.Items.Add(ei);
}
}
cnn.Close();
}
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<object>();
combobox1.ValueMember = "Id";
combobox1.DisplayMember = "FullName";
while (dr.Read())
{
list.Add(
new {
FullName = dr.GetString(1) + " " + dr.GetString(2),
Id = dr.GetInt32(0)
});
}
combobox1.DataSource = list;
Items.Insert
is looking for you to Insert at a specific point in the ComboBox list.
You want to use Items.Add
comboBox1.Items.Add(dr.GetString(1) + dr.GetString(2) + dr.GetInt32(0));
If you want to use Insert
it would need to be something like this:
comboBox1.Items.Insert(0, dr.GetString(1) + dr.GetString(2) + dr.GetInt32(0));