动态LinkBut​​ton的OnClick功能?

时间:2019-01-28 10:48:23

标签: asp.net vb.net

我正在创建动态LinkBut​​ton,在其中我为它动态分配一个ID,现在我可以编写一个onClick函数来获取该ID,但是尝试进行类似的操作后却没有结果:< / p>

  table.Append("<td><asp:LinkButton runat=""server"" class=""edit btn btn-sm btn-default"" ID=" & reader.GetString("id") & " OnClient=""Delete_User""><i class=""fa fa-trash-o"" aria-hidden=""true""></asp:LinkButton></i></a>")

这是VB.NET代码

Sub Delete_User(sender As Object, e As EventArgs)
    Dim clickedBtn As LinkButton = CType(sender, LinkButton)

    MsgBox(clickedBtn.ID)

End Sub

1 个答案:

答案 0 :(得分:2)

LinkButton是一个服务器控件,您无法以与从代码隐藏中呈现纯HTML标记相同的方式呈现它,它将无法按预期工作。您需要提供HtmlTableCell实例并从那里绑定LinkButton控件,假设table被定义为HtmlTable

' this is just a sample event
Protected Sub SomeEventHandler(sender As Object, e As EventArgs)

    Dim table As HtmlTable = New HtmlTable()
    Dim row As HtmlTableRow = New HtmlTableRow()

    ' set the data reader from database here

    Dim cell As HtmlTableCell = New HtmlTableCell()

    Dim linkbtn As LinkButton = New LinkButton()
    linkbtn.ID = reader.GetString("id")                ' setting control ID
    linkbtn.Text = "Delete User"                       ' setting link text
    linkbtn.CssClass = "edit btn btn-sm btn-default"
    AddHandler lnkbutton.Click, AddressOf Delete_User  ' assign event handler

    ' add the control to table cell ('td' element)
    cell.Controls.Add(linkbtn)
    row.Cells.Add(cell)
    table.Rows.Add(row)

    ' other stuff
End Sub

请注意,您应为服务器端点击事件提供Click属性,该属性与OnClick事件相关联,而不是OnClientOnClientClick

附加说明:

MsgBox不能在ASP.NET中使用,因为它属于WinForms,您需要提供JS alert()函数以显示带有RegisterStartupScriptRegisterClientScriptBlock的消息框:< / p>

Sub Delete_User(sender As Object, e As EventArgs)
    Dim clickedBtn As LinkButton = CType(sender, LinkButton)

    Dim message As String = "alert('" & clickedBtn.ID & "');"

    Page.ClientScript.RegisterClientScriptBlock(Me.[GetType](), "MsgBox", message, True)
End Sub

相关问题:

How to add linkbutton control to table cell dynamically

Creating a link button programmatically

How to add dynamically created buttons to a dynamically created table?