Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 914
Susan Avatar asked Aug 05 '11 14:08

Susan


People also ask

How Show dropdown list with selected value from database in asp net?

You have to use SelectedValue property of DropDownList . DataTextField and DataValueField are for specifying which properties from DataSource should be used as Text and Value of drop down list. Save this answer.

How do I get the selected value of dropdown?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

How do I select a specific item in a DropDownList?

In order to be able to select an item and have the value updated to the database, in the DropDownList add the AutoPostBack property and set it to true. Then, add the OnSeletedIndexChanged property and choose the 'create new event' option. It will created a method automatically in the <filename>. aspx.


2 Answers

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.

like image 58
Felan Avatar answered Oct 20 '22 23:10

Felan


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.

like image 26
Justin M. Keyes Avatar answered Oct 21 '22 01:10

Justin M. Keyes