我正在構建一個C#Windows窗體應用程序,我想讓用戶單擊類別按鈕,然後顯示相關的類別產品按鈕。但我嘗試了很多次,但又發生錯誤。 Image 1,Image 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);
}
}
您沒有名爲Bakery的列。你應該使用參數來避免sql注入和格式化問題。 – LarsTech
但我已經在我的數據庫中有名爲Bakery的列。 http://i.stack.imgur.com/viT2g.png – Clement
如果您的b.Text沒有引號,查詢會認爲它正在查看一列。因此,請始終使用參數。順便說一句,你沒有一個*列*名爲Bakery,你有*數據*。 – LarsTech