Search code examples
asp.netvb.netwebformslinkbutton

Dynamically generated Linkbutton does not fire Onclick event VB.Net


I have followed some of the instructions to create a new LinkButton at runtime with an event trigger and add an event handler for the LinkButton generated. I have no idea why the new LinkButton does not trigger the event added to it. Anyone please guide/correct me.

This is what I have right now.

ASPX:

<form id="myForm" runat="server">
 <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

 <asp:UpdatePanel ID="UpdatePanel1" runat="server">

 <ContentTemplate>

 <table class="mel-table" style="text-align: center" runat="server" id="mytab1">

    <tbody>
        <tr>
            <td>Case Number :</td>

            <td>
            <asp:TextBox ID="caseNumber" runat="server"></asp:TextBox>
            </td>

        </tr>

    </tbody>
  </table>

   <asp:Button OnClick="btnOK1_Click" ID="btnOK1" runat="server" Text="Save" />

  </ContentTemplate>

  </asp:UpdatePanel>
 </form>

ASPX.VB:

Protected Overloads Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Session("tablecontent") IsNot Nothing Then
        mytab1 = CType(Session("tablecontent"), HtmlTable)
    End If
End Sub

Public Function checking() As Boolean

        Dim caseNo As Double
            Try
                caseNo = Convert.ToDouble((caseNumber.Text).Trim())
            Catch ex As Exception
            caseNo = 0
            End Try

        Dim r As New HtmlTableRow
        Dim c0 As New HtmlTableCell
        r.Cells.Add(c0)

        Dim but As New LinkButton
        but.ID = caseNo 
        but.Text = caseNo.ToString() 
        AddHandler but.Click, AddressOf LinkButton1_Click
        c0.Controls.Add(but)

        mytab1.Rows.Add(r)
        Session("tablecontent") = mytab1
        Return True
End Function

Protected Sub LinkButton1_Click(sender As Object, e As EventArgs)

    'My Code here

End Sub

Protected Sub btnOK1_Click(sender As Object, e As EventArgs)

    If (checking()) Then

        ScriptManager.RegisterStartupScript(Page, Page.GetType, "Alert", "<script type='text/javascript'>alert('Success');</script>", False)

    End If

End Sub

Solution

  • When you click on the "Save" button, save the data in either local storage or database and try to load the page again to fill the page with the content from the storage. In this case, you can have the content on the page and so, you can utilize the events also.