Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem getting commandeventargs in command event following re-creationg of controls in postback

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();
    }
}
like image 867
dice Avatar asked Dec 06 '25 15:12

dice


1 Answers

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.

like image 106
Ruslan Avatar answered Dec 08 '25 04:12

Ruslan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!