I'm testing out two ImageButton controls one is set programmatically inside a GridView_RowDataBound function and the other is hard-coded on the client side as follows:
Static ImageButton (Works and fires ImageButton_Click):
<asp:ImageButton OnClick="ImageButton_Click" runat="server" ID="Foo" ImageUrl="images/edit-icon.png" />
Dynamic ImageButton (Does not work, won't fire ImageButton_Click):
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
.
.
.
ImageButton i = new ImageButton();
i.ImageUrl = "/images/edit-icon.png";
i.ID = "icon_" + testID.ToString();
i.ToolTip = "Click to add a new comment";
i.Click += new ImageClickEventHandler(ImageButton_Click);
e.Row.Cells[5].Controls.Add(i);
.
.
.
}
The Dynamic ImageButton renders as follows
<input type="image" name="GridView1$ctl24$DGV1$ctl02$icon_1234" id="GridView1_ctl24_DGV1_ctl02icon_1234" title="Click to add a new comment" src="/images/edit-icon.png" onclick="ImageButton_Click;WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("GridView1$ctl24$DGV1$ctl02$icon_1234", "", true, "", "", false, false))" style="border-width:0px;">
I notice the dynamic image button contains "onclick" vs the static imagebutton which has "OnClick", not sure if that makes a difference. I've been stumped on this for the last few hours, I don't know why the dynamic ImageButton is not firing. Please help.
UPDATE:
Thanks for all the feedback, I only need to process the ID of the ImageButton and it doesn't have to be server-side. Is there anyway I can do this from client-side using JavaScript in order to avoid postback? I tried re configuring the ImageButton as follows:
ImageButton i = new ImageButton();
i.ImageUrl = "/images/edit-icon.png";
i.ID = "icon_" + testID.ToString();
i.ToolTip = "Click to add a new comment";
i.OnClientClick = "submitComment(i.ID);return false;";
e.Row.Cells[5].Controls.Add(i);
I specify this function in the header of my web form
<head runat="server">
<script type="text/javascript">
submitComment(i.ID){
//Call WebMethod and pass comment along with this button's testID
}
</script>
</head>
But I get the following error when I click on the edit-icon ImageBtn:
Uncaught Reference Error: icon_12345 is not defined.
How is this so? If the edit-icons are already rendered and I'm just using client-side Javascript, shouldn't they already be defined and able to be properly referenced? This seems very counter intuitive to me. Am I missing something here? Is there some other control, besides and ImageButton, I can use for rendering the image without worrying about a postback, but that can still call the Javascript and pass along it's ID? What about using a regular Image control and just wiring it's onclick property to call the the submitComment function.
gv_RowDataBound()that shows WHY you are creating theImageButtondynamically, I can probably propose an alternative way to accomplish the same task without dynamically creating the control on every postback.