CommandEventArgs和事件问题 [英] CommandEventArgs and Event question

查看:66
本文介绍了CommandEventArgs和事件问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成了一些按钮,并在其上附加了一个事件处理程序,如下所示:

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

更新:

    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();
    }
}

推荐答案

动态生成按钮时通常是这种情况.页面回发时,页面不再具有按钮,因此无法将其绑定到事件处理程序.

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.

最简单的解决方案是确保在每次页面加载时重新生成Page_Init中的所有按钮.

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

这篇关于CommandEventArgs和事件问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆