views:

686

answers:

1

I've been racking my brain trying to get this to work. My event for my LinkButton isn't firing. I'm figuring that it has SOMETHING to do with ViewState and that the button is not there when it tries to fire the event after the Postback or something.

When I click the Add button,it adds the link to the page and then when I click the Diplay Time" linkbutton it should fire the event and display the CommandArgument data but it's not and i can't figure out why.

Here's my code:

<%@ Page Language="VB" %>

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

<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"&gt;
<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  A: 

The reason that's happening is that your dynamic button "lbn" needs to be drawn again on post back when it's clicked because the button doesn't exist after you click it.

Basically you just have to dynamically add the button to the page again on post back of click of that button.

I would recommend having the button already on the page but visible = false and then just showing it when you click the other button.

Avitus
@King: "I would recommend having the button already on the page but visible = false and then just showing it when you click the other button." - Yes, I'd agree except this is a very simple example of what I'm trying to do so this wouldn't be possible bc there could be an unlimited number of linkbuttons.
EdenMachine
if that is the case then what I'd do is instead of having a series of link buttons have a series of hyperlinks that onclick set a hidden variable and cause a postback of the page. Then in the page load check to see if the page isPostback and dependent of the contents of the variable do a function on the code behind.
Avitus
It gets pretty hairy but, yes if I add the controls on the Page_Load and then clear the panel if they click the button to add them again it works as it should - thanks!
EdenMachine