I have several dropdownlists and based on the user selection, I have to show the results retrieved from SQL in individual buttons [created dynamically]. I have a button click event which triggers the dynamic button creation.
CODE:
void CreateButtons(string val)
{
Button btn = new Button();
btn.Text = val;
Panel1.Visible = true;
btn.ID = val.Replace(" ", "_");
btn.Click += new System.EventHandler(test);
Panel1.Controls.Add(btn);
}
protected void Button1_Click(object sender, EventArgs e)
{
int cont = 0;
string[] names = new string[40];
string del2 = "MY SQL STATEMENT"
SqlCommand del1cmd2 = new SqlCommand(del2, conn);
SqlDataAdapter da = new SqlDataAdapter(del1cmd2);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
names[cont] = row.Field<string>(0);
CreateButtons(names[cont]);
}
Response.Write(names[cont]);
}
ISSUE:
I'm getting results from SQL, storing it on a data adapter and looping the CreateButtons function to create individual buttons for every single row returned. I'm able to get the desired result for button creation but the problem arises when I try to set an action for the buttons.
I need to set onclick event handler for all dynamically created buttons so that I'm able to give individuals actions for them.
When I click on the current code with new System.EventHandler statement, page refreshes and nothing happens, even though I have the below module.
public void test(object sender, EventArgs e)
{
Response.Write("Dynamic Button click event");
}
RESEARCH EFFORT: I have been looking up solutions for quite some time and I'm able to find working code with button creation in page load but haven't found a similar case with dynamic button creation on a button click event.