简体   繁体   English

如何在C#中使用点击处理以编程方式在C#中创建asp:button

[英]How to create an asp:button programmatically in c# behind with click handling

i write this code after many search but is not working 经过多次搜索后我写了这段代码,但无法正常工作
i need to create as asp:button programmatically and handling it 我需要以编程方式创建asp:button并对其进行处理

for(int i=0;i<DtShow.Rows.Count;i++)
        {
            Button btn = new Button
            {
                Text = "حذف",
                ID = i.ToString(),
                UseSubmitBehavior = false,
                CommandArgument =i.ToString(),
                CssClass = "btn btn-danger"
            };
            btn.Click +=new EventHandler(this.btn_Click);
            lstAccessDgv.Rows[i].Cells[2].Controls.Add(btn);
        }
 protected void btn_Click(object sender, EventArgs e)
    {
        Button b = (Button)sender;
        int id = Convert.ToInt32(b.ID);
        DtCode.Rows.RemoveAt(id);
        DtShow.Rows.RemoveAt(id);
        lstAccessDgv.Rows[id].Visible = false;
    }

why not call btn_Click? 为什么不致电btn_Click?

Unfortunately your question doesn't make it clear what information you're looking for, however, since you did make a specific query, I'll address that. 不幸的是,您的问题并未明确您要查找的信息,但是,由于您确实进行了特定查询,因此我将为您解决。

why not call btn_Click? 为什么不致电btn_Click?

Because the btn_Click event handler hasn't been bound to the button's click event. 因为btn_Click事件处理程序尚未绑定到按钮的click事件。

That's why you need to do this when you create the button: 这就是创建按钮时需要这样做的原因:

btn.Click +=new EventHandler(this.btn_Click);

This executes btn_Click when the button is clicked. 单击按钮时,它将执行btn_Click

A thing to keep in mind, though, is that this function will execute for every button in the list so you need to make sure it does work that specifically relates to the list item to which the button belongs. 但是要记住,此功能将对列表中的每个按钮执行,因此您需要确保其确实与该按钮所属的列表项有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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