I'm building a C# Windows Form application that I would like to allow user to click the category button, and then show the related category product buttons. But I tried many times but it occurs error again. Image 1, Image 2
public void DisplayCategories()
{
var cmd = new SqlCommand("SELECT DISTINCT category FROM Products ORDER BY category ASC", con);
con.Open();
try
{
var da = new SqlDataAdapter(cmd);
var dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
var 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();
}
private void UpdateList(object sender, EventArgs e)
{
var b = (Button)sender;
SqlCommand subcmd = new SqlCommand("SELECT itemName FROM Products WHERE description = " + b.Text, con);
var subda = new SqlDataAdapter(subcmd);
var subdt = new DataTable();
subda.Fill(subdt);
foreach (var subdr in subdt.Rows)
{
var 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);
}
}