仅在另一个组合框选择后显示组合框中的更新值
当我从组合框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 [email protected]", 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上得到错误,它在当前上下文中不存在 –
对不起,我的错误是,在使用 – Steve
史蒂夫我错过了什么? –