简体   繁体   中英

Create buttons dynamically in asp.net page and fire click event to all buttons

I want to create buttons dynamically in asp.net page and wrote the code. Buttons created dynamically through below code.

List<string> category = new List<string>();
            category.Add("AAA");
            category.Add("BBB");
            category.Add("CCC");
            category.Add("DDD");
            category.Add("EEE");
            for (int i = 0; i < category.Count; i++)
            {
                TableRow tr = new TableRow();

                TableCell cl = new TableCell();
                TableCell cl2 = new TableCell();
                Button button = new Button();
                button.ID = "raid" + i;
                button.Text = category[i];
                button.Click +=button_Click;

 private void button_Click(object sender, EventArgs e)
        {
            Response.Write(sender.ToString());
        }

Now I want to add click events for all buttons and want to get which button click event has been fired. Any idea? Response.Write(sender.ToString()); OR Response.Write(e.ToString()); returns common properties.

You can use CommandArgument property.

button.ID = "raid" + i;
button.Text = category[i];
button.Click +=button_Click;
button.CommandArgument +=category[i];


private void button_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    string category = btn.CommandArgument;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM