我有一个名为 的组合框combobox1
,我想用它id
作为值和Name
显示名称填充它。我搜索并阅读了一些教程,发现此代码可在表单加载事件中使用,但它没有填充列表。我看到一个空的下拉菜单。关于我错在哪里的任何想法?
在我的数据库类中,我有这个功能。
public static void FillDropDownList(string Query, System.Windows.Forms.ComboBox DropDownName)
{
SqlDataReader dr;
SqlConnection myConnection = new SqlConnection(CONNECTION_STRING);
try
{
myConnection.Open();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
// Check whether the Drop Down has existing items. If YES, empty it.
if (DropDownName.Items.Count > 0)
DropDownName.Items.Clear();
SqlCommand cmd = new SqlCommand(Query, myConnection);
dr = cmd.ExecuteReader();
while (dr.Read())
DropDownName.Items.Add(dr[0].ToString());
Console.Write(DropDownName.Items.Add(dr[0].ToString()));
dr.Close();
}
在我的表格中,我称之为
private void sales_record_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(DBUtils.CONNECTION_STRING);
DBUtils.FillDropDownList("select id,Name from Farms", comboBox1);
}