[英]My combobox doesn't show data from database
我的组合框需要显示数据库中的数据,但显示为空。 在这里,您有我正在处理的代码,Visual Studio不显示任何错误,但是combobox显示为空,是否有任何提示?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
{
SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\Documents\basededadospap.mdf;Integrated Security=True;Connect Timeout=30");
try
{
cn.Open();
string query = "select * from fornecedor where nomefornecedor='" + comboBox1 + "'";
SqlCommand createCommand = new SqlCommand(query, cn);
SqlDataReader dr = createCommand.ExecuteReader();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
ExecuteReader
将返回一个阅读器,然后您必须使用该阅读器逐行读回结果,并相应地填充组合框。 例如,如果您的前叉表中有一个名为“ MyItem”的(不可为空)字符串列,则应编写如下内容:
using (SqlDataReader dr = createCommand.ExecuteReader())
{
int myItemOrdinal = dr.GetOrdinal("MyItem");
List<object> comboBoxRows = new List<object>();
while (dr.Read())
{
string myItem = dr.GetString(myItemOrdinal);
comboBoxRows.Add(myItem);
}
}
comboBox1.BeginInvoke(() => comboBox1.Items.AddRange(comboBoxRows.ToArray()));
最后一行填充了UI线程上的组合框,假设从数据库中读取行是在另一个线程上完成的(您需要执行此操作以使UI保持响应)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.