【发布时间】:2016-11-07 19:27:09
【问题描述】:
函数最初是这样的:
void fillLiguanea()
{
items = new List<string>();
this.liguanea_Lane2TableAdapter.Fill(this.pharmaciesDataSet3.Liguanea_Lane2);
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string query = "SELECT * FROM dbo.Liguanea_Lane2";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string scode = dr.GetString(dr.GetOrdinal("code"));
comboBox2.Items.Add(scode);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
考虑到后台工作人员,这就是现在的样子:
private List <string> items;
void fillLiguanea()
{
items = new List<string>();
this.liguanea_Lane2TableAdapter.Fill(this.pharmaciesDataSet3.Liguanea_Lane2);
try
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string query = "SELECT * FROM dbo.Liguanea_Lane2";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string scode = dr.GetString(dr.GetOrdinal("code"));
// comboBox2.Items.Add(scode);
items.Add(scode);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
以下是我的后台工作函数,它们已被编辑以填充相关的组合框,即组合框 2。 这是我的后台工作人员:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
fillLiguanea();
}
这是我的 RunWorker 已完成:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (comboBox4.SelectedIndex == 0)
{
foreach (var item in items)
{
comboBox2.Items.Add(item);
}
}
}
我的问题是我哪里出错了?代码应该做的是根据combox4索引的选择从我的数据库中填充comboBox2。目前没有任何反应。我哪里错了?
【问题讨论】:
-
你确定 comboBox4.SelectIndex 真的 == 0?
-
是的,因为目前该组合框中只有一个值
-
嗯...为什么不把测试改成 comboBox.SelectedIndex != -1
-
或者改为测试
comboBox.Items.Count == 1。 -
还是不行,想知道我的代码结构是否正确
标签: c# winforms backgroundworker