Event for Dynamically created Controls in ASP.Net

孤街醉人 提交于 2019-12-08 12:05:28

问题


I've created an application in which I've created Dynamic Controls on Click Event of a Button. But the dynamically created Control Event will not Fire on Click of it. Below is the Code I've written.

   ImageButton closeImage = new ImageButton();
        closeImage.ID = "ID"+ dr["ID"].ToString();
        closeImage.AlternateText = "Delete";
        closeImage.ImageUrl = "App_Themes/images/CloseButton.png";
        closeImage.Attributes.Add("style", "float:right;cursor:pointer;margin: -19px 1px -10px;");
        closeImage.EnableViewState = true;
        closeImage.CommandName = "Delete";
        closeImage.CommandArgument = dr["ID"].ToString();
        closeImage.Attributes.Add("runat", "server");
        closeImage.OnClientClick = "return confirm('Are you sure you want to remove this');";
        closeImage.Click += new ImageClickEventHandler(this.closeImage_click);


  protected void closeImage_click(object sender, ImageClickEventArgs e)
{
    ImageButton ibDel = (ImageButton)sender;
}

The same code work if its placed on Page_Load(). Is there any other Solution to fire the event.


回答1:


I would like to suggest that you read up on the following article on MSDN. It's about page lifecycle.The key part is to when controls are created. If the controls are created in the wrong stage, events will not be registered, and thus will not fire.

http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.80%29.aspx



来源:https://stackoverflow.com/questions/9485800/event-for-dynamically-created-controls-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!