C# Dynamically created LinkButton Command Event Handler

点点圈 提交于 2019-12-12 14:31:17

问题


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.

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.

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?

Thanks!


回答1:


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.

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

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



回答2:


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.




回答3:


 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
    {

    }
}



回答4:


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:

        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.



来源:https://stackoverflow.com/questions/141169/c-sharp-dynamically-created-linkbutton-command-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!