我正在创建动态LinkButton,在其中我为它动态分配一个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
答案 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
事件相关联,而不是OnClient
或OnClientClick
。
附加说明:
MsgBox
不能在ASP.NET中使用,因为它属于WinForms,您需要提供JS alert()
函数以显示带有RegisterStartupScript
或RegisterClientScriptBlock
的消息框:< / 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?