首先,使用Add
将项目添加到ComboBox
. 其次,我更喜欢在表单中立即anonymous type
填写ComboBox
您使用纯原生Sql
和简单的内容。DataReader
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();
}
更新:
我注意到天真地添加到Item
列表中是行不通的!相反,应该将DataSource
属性设置为所需的列表。ComboBox
所以工作代码如下:
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;