簡體   English   中英

在ASP.NET頁面中動態創建按鈕,並對所有按鈕觸發點擊事件

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

我想在asp.net頁面中動態創建按鈕並編寫代碼。 通過以下代碼動態創建的按鈕。

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());
        }

現在,我想為所有按鈕添加單擊事件,並想要獲取觸發了哪個按鈕單擊事件。 任何想法? Response.Write(sender.ToString()); 或Response.Write(e.ToString()); 返回通用屬性。

您可以使用CommandArgument屬性。

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM