2016-05-03 25 views
0

我正在構建一個C#Windows窗體應用程序,我想讓用戶單擊類別按鈕,然後顯示相關的類別產品按鈕。但我嘗試了很多次,但又發生錯誤。 Image 1Image 2如何在C#Windows窗體中顯示按鈕的相關類別?

public void DisplayCategories() 
    { 
     SqlCommand cmd = new SqlCommand("SELECT DISTINCT category FROM Products ORDER BY category ASC", con); 
     con.Open(); 
     try 
     { 
      SqlDataAdapter da = new SqlDataAdapter(cmd); 
      DataTable dt = new DataTable(); 
      da.Fill(dt); 

      foreach (DataRow dr in dt.Rows) 
      { 
       Button b = new Button(); 
       b.Size = new Size(180,36); 
       b.BackColor = SystemColors.Control; 
       b.FlatStyle = FlatStyle.Flat; 
       b.UseVisualStyleBackColor = false; 
       b.Text = dr["category"].ToString(); 
       b.Click += new EventHandler(UpdateList); 
       flpCategory.Controls.Add(b); 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, "Error"); 
     } 
     con.Close(); 
    } 

    void UpdateList(object sender, EventArgs e) 
    { 
     Button b = (Button)sender; 
     SqlCommand subcmd = new SqlCommand("SELECT itemName FROM Products WHERE description = " + b.Text, con); 

     SqlDataAdapter subda = new SqlDataAdapter(subcmd); 
     DataTable subdt = new DataTable(); 
     subda.Fill(subdt); 

     foreach (DataRow subdr in subdt.Rows) 
     { 
      Button b2 = new Button(); 
      b2.Size = new Size(180, 50); 
      b2.BackColor = SystemColors.Control; 
      b2.FlatStyle = FlatStyle.Flat; 
      b2.UseVisualStyleBackColor = false; 
      b2.Text = subdr["itemName"].ToString(); 
      flpItems.Controls.Add(b2); 
     } 
    } 
+0

您沒有名爲Bakery的列。你應該使用參數來避免sql注入和格式化問題。 – LarsTech

+0

但我已經在我的數據庫中有名爲Bakery的列。 http://i.stack.imgur.com/viT2g.png – Clement

+0

如果您的b.Text沒有引號,查詢會認爲它正在查看一列。因此,請始終使用參數。順便說一句,你沒有一個*列*名爲Bakery,你有*數據*。 – LarsTech

回答

1

當你要搜索類型的文本字段像你description場,那麼你需要把尋找單引號之間的值。

SELECT itemName FROM Products WHERE description = 'Bakery' 

但是這將是錯誤的,因爲創建此查詢的最佳方式是通過參數化方法

string cmdText = "SELECT itemName FROM Products WHERE description = @desc"; 
Button b = (Button)sender; 
SqlCommand subcmd = new SqlCommand(cmdText, con); 
subCmd.Parameters.Add("@desc", SqlDbType.NVarChar).Value = b.Text; 
SqlDataAdapter subda = new SqlDataAdapter(subcmd); 
DataTable subdt = new DataTable(); 
subda.Fill(subdt); 

參數化查詢避免the Sql Injection hack和刪除需要檢查,如果你的字符串值包含單個引用。 (沒有加倍報價的語法錯誤)

+0

我明白了,這是工作。非常感謝。 :-) – Clement

+0

很高興能有所幫助。作爲一名新用戶,我建議閱讀[如何接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Steve

相關問題