[英]only show the updated values in combo box after another combo box selection
當我從組合框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();
}
}
}
您應該從第一個組合的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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.