ASP.Net Button in codebehind that calls codebehind function
I'm using Telerik RadControls, in my codebehind I have the following function开发者_开发技巧, a portion of which adds buttons to the footer.
Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As GridItemEventArgs)
If TypeOf e.Item Is GridDataItem Then
Dim editLink As HyperLink = DirectCast(e.Item.FindControl("EditLink"), HyperLink)
editLink.Attributes("href") = "#"
editLink.Attributes("onclick") = [String].Format("return ShowEditForm('{0}','{1}');", e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("ID"), e.Item.ItemIndex)
End If
''Add buttons to footer of grid
If TypeOf e.Item Is GridFooterItem Then
Dim footerItem As GridFooterItem = e.Item
''Creat Ticket button
Dim btn1 As New Button()
btn1.Text = "Create Ticket"
btn1.Attributes.Add("runat", "server")
btn1.Attributes.Add("OnClick", "btnCreate_Click")
footerItem.Cells(2).Controls.Add(btn1)
''Show All Tickets button
Dim btn2 As New Button()
btn2.Text = "Show All Tickets"
btn2.Attributes.Add("runat", "server")
btn2.Attributes.Add("OnClick", "btnAll_Click")
footerItem.Cells(2).Controls.Add(btn2)
End If
End Sub
Along with this I have the following two functions in my codebehind that I wish to call when the buttons get clicked.
Protected Sub btnCreate_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Redirect("itrequest.aspx", False)
End Sub
Protected Sub btnAll_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Response.Redirect("itall_v2.aspx", False)
End Sub
My problem is that these functions are not getting called in the rendered page. What's confusing me is that when I define these button with the same attributes in markup, they work fine. I don't understand what the difference is between defining the buttons in markup vs code behind. Why aren't these functions getting called from the buttons that I define in the code behind? The buttons that do work and that I have commented out in my markup for testing purposes are as follows.
<%--<asp:Table ID="Table2" runat="server" HorizontalAlign="Left">
<asp:TableRow>
<asp:TableCell>
<br />
<asp:Button ID="Button1" runat="server" Text="Create Ticket" OnClick="btnCreate_Click" />
<asp:Button ID="Button2" runat="server" Text="Show All Tickets" OnClick="btnAll_Click" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>--%>
Attributes.Add() function is used to add HTML attributes to elements in the page. So you are adding client side script in your code. To add a code behind event to your button, use should use the following code:
btn1.Click += new EventHandler(btn1_Click);
nandokakimoto is correct, but the syntax in VB is:
AddHandler btn1.Click, AddressOf btn1_Click
A strange syntax where you don't use brackets even though AddHandler appears to be a function.
Regards
精彩评论