Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CommandEventArgs and Event question

Tags:

c#

asp.net

events

I generated a few buttons and attached to them an eventhandler like this:

Button pgs = new Button();//Create New Topic
pgs.Width = 20;
pgs.Command += obtainTopicsPerPage_Click;
pgs.CommandName = tPage.ToString();
pgs.Text = tPage.ToString();
btns.Add(tPage.ToString());
buttons.Add(pgs);
}

void obtainTopicsPerPage_Click(Object sender, CommandEventArgs e)
{
    foreach (var item in tPages)
    {
        if (item.Key == e.CommandName)
        {
            foreach (var posts in item.Value)
            {
                posts.ExecuteAll();
             }
        }
    }
    MyButtonTable();
}

Now, the eventhandler never triggers when i click on the button. i check with the debugger,,and when i click the button, there is only a postback,,but it doesnt reach inside the eventhandler functoin

Update:

    void Page_PreInit(object sender, EventArgs e)
{
    List<Button> btn=(List<Button>)ViewState["Buttons"];
    foreach (var item in btn)
    {
            item.Width = 20;
            item.Command += obtainTopicsPerPage_Click; //resigning the eventhandlers from the begining
             item.CommandName = tPage.ToString();
             item.Text = tPage.ToString();
    }
}
like image 948
Matrix001 Avatar asked Oct 10 '22 18:10

Matrix001


1 Answers

This is often the case when dynamically generating the buttons. When the page posts back, the page doesn't have the buttons any more and therefore can't bind them to the event handlers.

The simplest solution is to make sure you re-generate all the buttons in the Page_Init on every load of the page.

like image 103
Robin Day Avatar answered Oct 14 '22 04:10

Robin Day