如何在ASP.NET中使用OnCommand应用AddHandler

时间:2009-06-15 19:04:09

标签: asp.net events addhandler

我一直绞尽脑汁想要让它发挥作用。我的LinkBut​​ton活动没有解雇。我正在确定它与ViewState有关,并且当它在Postback之后尝试触发事件时按钮不存在。

当我单击“添加”按钮时,它会添加到页面的链接,然后当我单击“Diplay Time”链接按钮时,它应该触发事件并显示CommandArgument数据,但它不是,我无法找出原因。< / p>

这是我的代码:

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    End Sub

    Protected Sub btnDelete_OnCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)
        Response.Write(e.CommandArgument)
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim btn As New LinkButton()
        btn.ID = "lbn"
        btn.Text = "Display Time"
        btn.ValidationGroup = "vgDeleteSigner"
        AddHandler btn.Command, AddressOf btnDelete_OnCommand
        btn.CommandArgument = Now.TimeOfDay.ToString()
        btn.EnableViewState = True
        Panel1.Controls.Add(btn)
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        <asp:Panel ID="Panel1" runat="server">
        </asp:Panel>
    </div>
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

发生这种情况的原因是,点击后需要在回发后再次绘制动态按钮“lbn”,因为单击后该按钮不存在。

基本上你只需要在点击该按钮的帖子后再次动态地将按钮添加到页面。

我建议在页面上显示按钮,但显示为false,然后在单击其他按钮时显示该按钮。