我如何动态地添加按钮ASP.NET激发事件? [英] How do I get dynamically added ASP.NET buttons to fire events?

查看:83
本文介绍了我如何动态地添加按钮ASP.NET激发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个简单的问题,但我不是一个ASP.NET开发人员,我感到很卡住了。

我有一个零和几百个结果之间返回一个简单的搜索程序。每一种必须添加到网页作为一个按钮,我想设置按钮的文本和CommandArgument属性,这样点击按钮时,我可以读CommandArgument背部和相应的反应。

然而,当我点击按钮的事件不会运行在所有。我怎样才能得到它运行?

构建按钮列表(简化了可读性)的code是如下:

 的foreach(在SearchResult所SearchResult中SR)
    {
        巴顿结果=新的Button();
        result.Text = sr.name;
        result.CommandArgument = sr.ID.ToString();
        AccountSearchResults.Controls.Add(结果);
        result.Click + =新的EventHandler(SearchResultClicked);
        AccountSearchResults.Controls.Add(新LiteralControl(< BR />中));
    }

在分钟测试,我已经出现在表单上的标签把CommandArgument。这code从不虽然执行。

 无效SearchResultClicked(对象发件人,EventArgs的发送)
    {
        Label1.Text =((按钮)发送方).CommandArgument;
    }


解决方案

您中单击按钮时要添加这些另一种答案提及。看着你code,我建议你尝试设置一个唯一的ID为每个按钮添加,然后确保在加载具有相同ID和CommandArgument值按钮重新加载页面。当点击一个动态加载的按钮,它仍然必须在页面上存在回发后的事件触发。

我觉得ID是你所需要的,再加上你的CommandArgument要求)。你可以把ID信息在ViewState,如果你不能得到它没有重复漫长搜索过程。

This is probably a simple question but I am not an ASP.NET developer and I am quite stuck.

I have a simple search routine that returns between zero and several hundred results. Each of these must be added to the page as a button and I want to set the text of the button and the CommandArgument property so that when the button is clicked I can read the CommandArgument back and react accordingly.

However, when I click the button the event does not run at all. How can I get it to run?

The code for building the button list (simplified for readability) is as follows:

    foreach (SearchResult sr in searchResults)
    {
        Button result = new Button();
        result.Text = sr.name;
        result.CommandArgument = sr.ID.ToString();
        AccountSearchResults.Controls.Add(result);
        result.Click += new EventHandler(SearchResultClicked);
        AccountSearchResults.Controls.Add(new LiteralControl("<br/>"));
    }

At the minute to test, I have popped a label on the form to put the CommandArgument in. This code is never executed though.

   void SearchResultClicked(object sender, EventArgs e)
    {
        Label1.Text = ((Button)sender).CommandArgument;
    }

解决方案

You mentioned in another answer that you are adding these when a button is clicked. Looking at your code, I would suggest that you try setting a unique ID for each button added, then ensure that on loading the page that buttons with the same IDs and CommandArgument values are reloaded. When a dynamically loaded button is clicked, it must still exist on the page after postback for the event to fire.

I think the ID is all you need, plus your requirement for the CommandArgument). You could put the ID information in the ViewState if you can't get it repeat without a long search process.

这篇关于我如何动态地添加按钮ASP.NET激发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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