我们需要通过从另一个组合框中选择值来向组合框添加值。 它不会选择应有的值。只有第一个if部分执行。 这是代码: 它对我们不起作用。
private void section_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = (string)section.SelectedItem;
if(selected == "Giftarticles")
{
SqlConnection conn1 = new SqlConnection(connString);
conn1.Open();
string itemc = "(select distinct Itemcode from Items where Section1 like 'G%' )except(select distinct Itemcode from Items where Section1 like 'H%')";
SqlCommand cmditem = new SqlCommand(itemc, conn1);
SqlDataReader dr2 = cmditem.ExecuteReader();
while (dr2.Read())
{
itemcode.Items.Add(dr2["Itemcode"].ToString());
}
dr2.Close();
conn1.Close();
}
else
{
SqlConnection conn2 = new SqlConnection(connString);
conn2.Open();
string itemc1 = "(select distinct Itemcode from Items where Section1 like 'H%')except(select distinct Itemcode from Items where Section1 like 'G%')";
SqlCommand cmditem = new SqlCommand(itemc1, conn2);
SqlDataReader dr2 = cmditem.ExecuteReader();
while (dr2.Read())
{
itemcode.Items.Add(dr2["Itemcode"].ToString());
}
dr2.Close();
conn2.Close();
}
}
答案 0 :(得分:0)
我看到,if的实际需要介于
之间 string itemc = "(select distinct Itemcode from Items where Section1 like 'G%' )except(select distinct Itemcode from Items where Section1 like 'H%')";
和
string itemc1 = "(select distinct Itemcode from Items where Section1 like 'H%')except(select distinct Itemcode from Items where Section1 like 'G%')";
扫描这两个,其余的显示相同。因此,只有查询必须不返回结果给您。独立运行这些查询,看看你是否得到了secon的结果。
答案 1 :(得分:0)
虽然我讨厌在代码中直接使用Connection,Reader等,并建议使用Typed DataSet方式,这里应该适用于你:
private void section_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = (string)section.SelectedItem;
using(SqlConnection conn1 = new SqlConnection(connString))
{
conn1.Open();
string itemc = "select distinct Itemcode from Items where Section1 like 'G%'";
if(selected != "Giftarticles") itemc += " AND Section1 NOT LIKE 'H%'"
SqlCommand cmditem = new SqlCommand(itemc, conn1);
SqlDataReader dr2 = cmditem.ExecuteReader();
while (dr2.Read())
itemcode.Items.Add(dr2["Itemcode"].ToString());
dr2.Close();
conn1.Close();
}
}
用此替换上述全部代码。