views:

5732

answers:

2

I have an ASP.NET webform on which I use a DropDownList control to allow the user to select an item and see related results. For some reason when I set the SelectedValue property of the DropDownList the value it's set to is not immediately available.

Here's my code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        DropDownList1.SelectedValue = "5";
        BindView();
    }
}

protected void BindActivities()
{
    DataClassesDataContext dc = new DataClassesDataContext();
    var query = from activity in dc.Activities
                where activity.AssignedTo == Convert.ToInt32(DropDownList1.SelectedValue);
    GridView1.DataSource = query;
    GridView1.DataBind();
}

In the previous code I get an error that DropDownList1.SelectedValue is null. The wierd thing is that if I comment out the code that uses DropDownList1.SelectedValue and let the page load, DropDownList1 is actually set to value 5. So it looks like it's getting set correctly but is just not immediately available. The debugger confirms that DropDownList.SelectedValue is not set to 5 immediately after the line of code that sets it.

Any ideas what is going on here?

+4  A: 

Are you setting the value before you have bound the dropdown list?

Paddy
The DropDownList is being declaratively bound to a LinqDataSource control. I think thought happens before the Page_Load event. Is that correct?
joshb
Not unless you explicitly call it.
Matthew Jones
I added an explicit call to DropDownList1.DataBind() immediately before setting the SelectedValue and it works as I expected now.
joshb
+1  A: 

Yes the user above is right

if (!Page.IsPostBack) { BindView(); DropDownList1.SelectedValue = "5"; }

... should work just fine.

There is no such thing as a delay in execution, just the order of execution.

Theofanis Pantelides