0

我们需要通过从另一个组合框中选择值来将值添加到组合框。它没有按应有的方式选择值。只有第一个 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();
}
    }
4

2 回答 2

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%')";

.

除了这两个,其余看起来都一样。因此,只有查询不能向您返回结果。独立运行这些查询,看看你是否得到第二个查询的结果。

于 2013-03-25T06:43:37.153 回答
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();
    }
}

用这个替换你上面的整个代码。

于 2013-03-25T06:47:48.093 回答