动态创建的html控件-检测点击事件? ASP.NET C#

时间:2018-08-19 08:59:53

标签: c# asp.net

我正在Asp.net(C#)中的一个项目上工作,我有以下代码(C#)在运行时动态生成html按钮(针对列表中的每个项目):

在我的.aspx文件中:

<div id="myDiv" runat="server" ...></div>

在我的.aspx.cs文件中:

List<Item> list;

private void Display()
{
    foreach (Item item in list)
        AddButton(item);
}

private void AddButton(Item item)
{
    HtmlButton button = new HtmlButton();
    button.InnerText = item.Content;
    button.ID = item.name; 
    button.ServerClick += new EventHandler(Item_Click);
    myDiv.Controls.Add(button);
}

private void Item_Click(Object sender, EventArgs e)
{
    // HERE I WANT TO DO SOMETHING ON THE SPECIFICALLY
    // CLICKED BUTTON,
    // THE PROBLEM IS THAT I CAN'T KNOW WHICH BUTTON OF
    // THE DYNAMICALLY ADDED BUTTONS (BY THE AddButton()
    // FUNCTION) IS CLICKED, NOTE: I HAVE MORE THAN 10 ITEMS IN 
    // list. I MEAN I CAN'T PASS THE CLICKED BUTTON AS A                                              
    // PARAMETER TO THIS Item_Click FUNCTION, IN GENERAL, WHAT I
    // WANT IS SOMETHING LIKE:

    // Item_Click(Object sender, EventArgs e, HtmlButton clickedButton)

    // WITH SUCH DECLARATION OF Item_Click FUNCTION I CAN DO WHAT 
    // I WANT ON THE CLICKED BUTTON, BUT IT DOESN'T WORK THAT
    // WAY, BECAUSE EventHandler's PARAMETERS ARE: Object,      
    // EventArgs, AND IT WOULD NOT HELP ME TO CREATE MY CUSTOM
    // EVENTHANDLER BECAUSE HtmlButton.ServerClikc IS OF TYPE
    // EventHandler.
}

有什么建议吗?

感谢帮助!

1 个答案:

答案 0 :(得分:2)

您必须在不使用if(!IsPostBack)

的情况下填写page_load中的列表
void Page_Load(object sender, EventArgs e )
{
     // don`t use if(!IsPostBack) because every postback your contols leave and you must register your controls.
     list=new List<Item>();
     list.Add(...);
     list.Add(...);
     list.Add(...);

}