2016-03-26 27 views
0

當我從組合框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(); 
     } 
    } 
} 
+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 [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; 
} 
+0

在sqlconnection.open上出現錯誤,它在當前上下文中不存在! –

+0

在sqlcmd2.parameters上得到錯誤,它在當前上下文中不存在 –

+1

對不起,我的錯誤是,在使用 – Steve

相關問題