views:

47

answers:

2

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?

+3  A: 

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!

Tahbaza
@Tahbaza: so its because of the lifecycle... I must have confused it with something else. Back to the question: I do notice that the SelectedValue of the DropDownList wasnt saved after the page refreshes. Is there something I can use to save it so after the selection changes I can get the value and do something with it? Thanks.
BeraCim
`dropDown.SelectedValue` should contain the posted, current value of the dropdown list. Just be sure you aren't rebinding the dropdown, clearing it or something else in the page load or another event before your code that checks the selectedvalue has a chance to examine it.
Tahbaza
@Tahbaza: I managed to retrieve the value of the dropdownlist in the OnLoad method, but not the CreateChildControls. Also, OnLoad seemed to run after CreateChildControls in my scenario.
BeraCim
A: 

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.

Gary