简体   繁体   中英

SelectedIndexChanged for DropDownList in ASP.NET firing in the wrong order

I've got the following DropDownList in my code that is firing in the wrong order:

public class MyWebpart : WebPart
{
    private DropDownList dropDown = new DropDownList();

    private string selectedValue;

    public Webpart()
    {
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        dropDown.AutoPostBack = true;
        dropDown.SelectedIndexChanged += new EventHandler(DropDown_SelectedIndexChanged);
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        this.EnsureChildControls();
    }

    protected void DropDown_SelectedIndexChanged(Object sender, EventArgs e)
    {
        selectedValue - dropDown.SelectedValue;
    }

    protected void override void CreateChildControls()
    {
        base.CreateChildControls();
        // create some stuff here
    }

I was expecting when the drop down selection changes, the DropDown_SelectedIndexChanged will get called first, but instead it went through the entire lifecycle going from OnInit, OnLoad, CreateChildControls, then DropDown_SelectedIndexChanged.

Am I missing something? How can I get DropDown_SelectedIndexChanged call first?

You can't change the page lifecycle. What you can do is either check if Page.IsPostBack and do something appropriate only on first load OR you can create a webservice and call that webservice from javascript to execute your selectedindexchanged actions in js rather than posting back the whole page.

Good luck!

This is you will call method

protected void override void CreateChildControls()
{
    base.CreateChildControls();
    dropDown.SelectedIndexChanged += new EventHandler(DropDown_SelectedIndexChanged);
}

Posted-back values are not accessible from CreateChildControls() ; you must wait until the OnLoad event for the posted back private view state to be loaded into controls.

In the OnInt event call EnsureChildControls() ; the posted-back values are then available in the controls in the OnLoad event – note: EnsureChildControls() invokes CreateChildControls() .

The dropDown.AutoPostBack = true; property triggers a postback which causes it to go through the page lifecycle events.

Your best bet is to put if(!IsPostBack) { } check in at least the OnLoad method to filter out events that you didn't want happening on the postback.

You could write some Javascript function and apply it to the 'onchange' event of the dropdownlist. But you'll need to turn off autopostback and it would happen on the client-side rather than on server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM