【问题标题】:only show the updated values in combo box after another combo box selection仅在选择另一个组合框后在组合框中显示更新的值
【发布时间】:2016-07-13 23:53:49
【问题描述】:

当我从组合框 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();
        }
    }
}

【问题讨论】:

  • 史蒂夫我错过了什么?

标签: c# sql sql-server combobox items


【解决方案1】:

您应该从第一个组合的 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;
}

【讨论】:

  • 在 sqlconnection.open 上出现错误,它在当前上下文中不存在!!
  • 在 sqlcmd2.parameters 上出现错误,它在当前上下文中不存在
  • 对不起,我的错误,删除了使用末尾的分号
  • using语句末尾的分号要去掉??
  • 再次修复,在第二个使用时缺少第二个右括号
猜你喜欢
  • 2013-05-07
  • 2017-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-08
相关资源
最近更新 更多