views:

291

answers:

2

I am haveing problems getting the command event args following the second click using the code below.

so - when i process a button click, and generate a new button to replace the one that was there i lose the viewstate on the next button click.

Any suggestions on what I need to do to get this to work? I cannot significantly change the structure as I must generate a variable number of totally un-related buttons in the command handler.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            LinkButton btn = new LinkButton();
            btn.ID = "btn1";
            this.Panel1.Controls.Add(btn);
            btn.Command += new CommandEventHandler(myLinkButton_Command);          
        }
        else
        {
            LinkButton btn = new LinkButton();
            btn.ID = "btn1";
            this.Panel1.Controls.Add(btn);
            btn.Text = "My Button 1";
            btn.CommandArgument = "1";
            btn.Command += new CommandEventHandler(myLinkButton_Command);
        }
    }

    void myLinkButton_Command(object sender, CommandEventArgs e)
    {
        int newArg = Convert.ToInt32(e.CommandArgument) + 1;// empty string on second mouse click
        this.Panel1.Controls.Clear();
        LinkButton myLinkButton = new LinkButton();          
        myLinkButton.ID = "btn1";
        this.Panel1.Controls.Add(myLinkButton);
        myLinkButton.Text = "My Button " + newArg.ToString();
        myLinkButton.CommandArgument = newArg.ToString();
    }
}
A: 

You have forgotten to set the CommandArgument property when you recreate the button in Page_Load.

Guffa
No need for that. The CommandArgument is preserved in a view state. The problem is a presence of a literal and change of buttons position in the controls collection
Ruslan
+3  A: 

This happens because your panel has a literal control in it. When you add your button the first time, it (the button) is a second control. When you later clear panel's controls collection, it becomes the first control and the viewstate is saved for the first control, which on following postback becomes the literal.

Simply convert

<asp:Panel ID="Panel1" runat="server">
</asp:Panel>

to

<asp:Panel ID="Panel1" runat="server" />

and it will work.

Ruslan
thanks - i dont think i would ever have thought of that. Hopefully this is similar to what is happening in my real project.
dice