C# 动态创建的 LinkBut​​ton 命令事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/141169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 15:14:33  来源:igfitidea点击:

C# Dynamically created LinkButton Command Event Handler

提问by spdevsolutions

So I have a weird situation here... I have an System.Web.UI.WebControls.WebParts.EditorPart class. It renders a "Search" button, when you click this button, it's clickHandler method does a DB search, and dynamically creates a LinkButton for each row it returns, sets the CommandName and CommandArgument properties and adds a CommandEventHandler method, then adds the LinkButton control to the page.

所以我在这里有一个奇怪的情况......我有一个 System.Web.UI.WebControls.WebParts.EditorPart 类。它呈现一个“搜索”按钮,当你点击这个按钮时,它的 clickHandler 方法会做一个数据库搜索,并为它返回的每一行动态创建一个 LinkBut​​ton,设置 CommandName 和 CommandArgument 属性并添加一个 CommandEventHandler 方法,然后添加 LinkBut​​ton 控件到页面。

The problem is, when you click a LinkButton, its CommandEventHandler method is never called, it looks like the page just posts back to where it was before the ORIGINAL "Search" button was pressed.

问题是,当您单击 LinkBut​​ton 时,它的 CommandEventHandler 方法从未被调用,看起来页面只是回发到原始“搜索”按钮被按下之前的位置。

I have seen postings saying that you need to add the event handlers in OnLoad() or some other early method, but my LinkButtons haven't even been created until the user tells us what to search for and hits the "Search" button... Any ideas on how to deal with this?

我看到一些帖子说您需要在 OnLoad() 或其他一些早期方法中添加事件处理程序,但是直到用户告诉我们要搜索的内容并点击“搜索”按钮时,我的 LinkBut​​ton 才被创建。 . 关于如何处理这个问题的任何想法?

Thanks!

谢谢!

回答by Mike J

You need to re-add the dynamically created controls, in the onload, so that they can be in the page hierarchy and fire their event.

您需要在 onload 中重新添加动态创建的控件,以便它们可以在页面层次结构中并触发它们的事件。

回答by Adrian Clark

This is my favorite trick :)

这是我最喜欢的技巧:)

Our scenario is to first render a control. Then using some input from the user, render further controls and have them respond to events.

我们的场景是首先渲染一个控件。然后使用来自用户的一些输入,呈现更多控件并让它们响应事件。

The key here is state - you need to know the state of the control when it arrives at PostBack - so we use ViewState. The issue becomes then a chicken-and-egg problem; ViewState isn't available until after the LoadViewState()call, but you must create the controls before that call to have the events fired correctly.

这里的关键是状态——你需要知道控件到达 PostBack 时的状态——所以我们使用 ViewState。那么问题就变成了鸡和蛋的问题;ViewState 直到LoadViewState()调用之后才可用,但您必须在调用之前创建控件才能正确触发事件。

The trick is to override LoadViewState()and SaveViewState()so we can control things.

诀窍是覆盖LoadViewState()SaveViewState()所以我们可以控制事情。

(note that the code below is rough, from memory and probably has issues)

(请注意,下面的代码很粗糙,从内存中可以看出并且可能有问题)

private string searchQuery = null;

private void SearchButton(object sender, EventArgs e)
{
    searchQuery = searchBox.Text;
    var results = DataLayer.PerformSearch(searchQuery);
    CreateLinkButtonControls(results);
}

// We save both the base state object, plus our query string.  Everything here must be serializable.
protected override object SaveViewState()
{
    object baseState = base.SaveViewState();
    return new object[] { baseState, searchQuery };
}

// The parameter to this method is the exact object we returned from SaveViewState().
protected override void LoadViewState(object savedState)
{
    object[] stateArray = (object[])savedState;

    searchQuery = stateArray[1] as string;

    // Re-run the query
    var results = DataLayer.PerformSearch(searchQuery);

    // Re-create the exact same control tree as at the point of SaveViewState above.  It must be the same otherwise things will break.
    CreateLinkButtonControls(results);

    // Very important - load the rest of the ViewState, including our controls above.
    base.LoadViewState(stateArray[0]);
}

回答by Protector one

A dirty hack I just came up with, is to create dummy LinkButtons with the same IDs as the real buttons. So let's say you are going to create a LinkButton "foo" at Pre_Render (which is too late), then also create a dummy foo at Page_Load:

我刚刚想到的一个肮脏的技巧是创建与真实按钮具有相同 ID 的虚拟 LinkBut​​ton。因此,假设您要在 Pre_Render 处创建一个 LinkBut​​ton "foo"(为时已晚),然后还在 Page_Load 处创建一个虚拟 foo:

        var link = new LinkButton();
        link.ID = "foo";
        link.Click += fooEventHandler;
        dummyButtons.Controls.Add(link);

(Where "dummyButtons" is just a PlaceHolder on the page with Visibility set to false.) It's ugly, but it works.

(其中“dummyButtons”只是页面上的一个 PlaceHolder,Visibility 设置为 false。)这很丑陋,但它有效。

回答by M.Rahmani

 LinkButton link= new LinkButton();
 link.Command +=new CommandEventHandler(LinkButton1_Command);

 protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
    try
    {
        System.Threading.Thread.Sleep(300);
        if (e.CommandName == "link")
        {
           //////////
        }
    }
    catch
    {

    }
}