Susan
Susan

Reputation: 1832

ASP.Net DropDownList selected value

I have a feeling I'm missing something really obvious, I'm not able to capture the selected value of my DropDownList; the value renaubs the first item on the list. I have set the DropListList autopostback property to true. I have a SelectedIndexChangedEvent which is pasted below. This is NOT on the master page.

protected void ddlRestCity_SelectedIndexChanged(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        r_city = ddlRestCity.SelectedValue.ToString();
    }
}

Here is the DropDownList control:

<asp:DropDownList ID="ddlRestCity" runat="server" 
        Width="100px" AutoPostBack="True" 
        onselectedindexchanged="ddlRestCity_SelectedIndexChanged">
</asp:DropDownList>

Thanx in advance for your help!

Upvotes: 10

Views: 27442

Answers (3)

Chains
Chains

Reputation: 13167

What is r_city?

If it's a textbox, then you need to do something like r_city.text = ...

Also -- you might consider removing your postback check. Usually, that's most useful in the page.onload event, and usually, you're checking for if NOT ispostback...

Upvotes: 0

Justin M. Keyes
Justin M. Keyes

Reputation: 6974

Where is your DataBind() call? Are you checking !IsPostBack before the call? For example:

protected void Page_Load(object sender, EventArgs e) {
    if (!IsPostBack) {
        ddlRestCity.DataSource = ...;
        ddlRestCity.DataBind();
    }
}

Explanation: If you don't check for !IsPostBack before DataBind(), the list will re-populate before SelectedIndexChanged is fired (because Page.Load fires before child events such as SelectedIndexChanged). When SelectedIndexChanged is then fired, the "selected item" is now the first item in the newly-populated list.

Upvotes: 8

Felan
Felan

Reputation: 1273

My off the cuff guess is you are maybe re-populating the list on a post back and that is causing the selected index to get reset.

Upvotes: 12

Related Questions