我正在开发visual studio 2012 c#... 我将值插入到combox中......我从数据库中取出它们...我想知道如何将一个项目添加到COMBOBOX中...生成下面的代码:
此函数用于填充组合框,其名称取自数据库包含名称和id中的表:
List<Lookup> fillCombo(string query, string column)
{
List<Lookup> lookups = new List<Lookup>();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Lookup lookupobject = new Lookup();
lookupobject.ID = Convert.ToInt32(reader["ID"]);
//if (reader["Name"] != DBNull.Value)
lookupobject.Name = reader[column].ToString();
lookups.Add(lookupobject);
}
conn.Close();
}
return lookups;
}
然后我按如下方式调用此函数:
lookups = fillCombo("select id,name from LookupDetails where LOOKUPID = (select id from Lookup where Name = 'users')", "name");
comboBox2.DataSource = lookups;
comboBox2.DisplayMember = "name";
答案 0 :(得分:0)
设置DataSource属性时,无法修改ComboxBox Items集合。
您可以选择修改List<Lookup>
,也可以通过迭代List<Lookup>
将项目添加到combox中。
以下是使用foreach循环在combobox中添加项目并在comboxbox的0索引处插入项目的选项:
lookups = fillCombo(@"select id,name from LookupDetails where LOOKUPID =
(select id from Lookup where Name = 'users')", "name");
foreach(var obj in lookups)
comboBox2.Items.Add(obj);
comboBox2.DisplayMember = "Name";
comboBox2.Items.Insert(0, "");
注意:在问题中提到的代码中,SqlDataReader
从未关闭,我通过包含using
语句对其进行了修改。在SqlDataReader
块中写下这些内容时,您不必关闭SqlConnection
或using
:
List<Lookup> fillCombo(string query, string column)
{
List<Lookup> lookups = new List<Lookup>();
string sConstring = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstring))
using(SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Lookup lookupobject = new Lookup();
lookupobject.ID = Convert.ToInt32(reader["ID"]);
//if (reader["Name"] != DBNull.Value)
lookupobject.Name = reader[column].ToString();
lookups.Add(lookupobject);
}
}
}
return lookups;
}