仅在另一个组合框选择后显示组合框中的更新值

时间:2016-03-26 08:36:50

标签: c# sql sql-server combobox items

当我从组合框1中选择项目时,它会在组合框2中显示项目。

当我从组合框1中选择另一个项目时,它会在组合框2中显示先前结果和新结果的项目

我只想在组合框2中显示新项目。当我从组合框1中选择项目时,应该更新组合框2并删除以前的项目。

private void cb_oname_SelectedIndexChanged(object sender, EventArgs e)
{
    SqlConnection sqlConnection = new SqlConnection(@"Data Source=.;Initial Catalog=Pizza Mania;Integrated Security=True");
    {
        SqlCommand sqlCmd2 = new SqlCommand("SELECT Product_category FROM Product2 where Product_Name='"+cb_oname.SelectedItem+"'", sqlConnection);
        {
            sqlConnection.Open();

            SqlDataReader sqlrdr = sqlCmd2.ExecuteReader();

            while (sqlrdr.Read())
            {
                cb_ocat.Items.add(sqlrdr["Product_category"].ToString());
                cb_ocat.Update();
            }

            sqlConnection.Close();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您应该从第一个组合的Items集合中删除selectedindex上的项目。

请注意,我还更改了代码,以便在一次性对象和参数周围使用正确的using语句,而不是使用非常危险的字符串连接

private void cb_oname_SelectedIndexChanged(object sender, EventArgs e)
{
    // Safety check, SelectedIndexChanged is called also when there is
    // no item selected (see later)
    if(cb_oname.SelectedIndex < 0)
        return;

    using(SqlConnection sqlConnection = new SqlConnection(.....))
    using(SqlCommand sqlCmd2 = new SqlCommand(@"SELECT Product_category 
                     FROM Product2 WHERE Product_Name=@name", sqlConnection))
    {
        sqlConnection.Open();
        sqlCmd2.Parameters.Add("@name", SqlDbType.NVarChar).Value = cb_oname.SelectedItem;

        using(SqlDataReader sqlrdr = sqlCmd2.ExecuteReader())
        {
            // Clear the previous items list
            cb_ocat.Items.Clear(); 
            while (sqlrdr.Read())
                cb_ocat.Items.Add(sqlrdr["Product_category"].ToString());
        }
    }
    // Remove from the Items collection, but it is not enough
    cb_oname.Items.RemoveAt(cb_oname.SelectedIndex);
    // Set the selectedindex to -1 so the current text in the combo is reset        
    cb_oname.SelectedIndex = -1;
}
相关问题