Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my DropDownList's SelectedItem only showing the first item in the list each time?

I am having a problem with an ASP.NET DropDownList which is populated by an XML file:

rblState.DataSource = dsState;
rblState.DataValueField = "abbreviation";
rblState.DataTextField = "name";
rblState.DataBind();

This works fine and displays all the right data however, the problem occurs when I try and retrieve the selected value from the list after a button has been clicked:

string state = rblState.SelectedItem.Text;
Console.WriteLine(state);

This always outputs only the first value within the list.

Anyone know the solution to this?

like image 445
RyanDreggs Avatar asked Dec 22 '22 05:12

RyanDreggs


2 Answers

You are probably re-binding the DataSource on PostBack. Instead, do this:

//only bind on the first request
if (!Page.IsPostBack)
{
    rblState.DataSource = dsState;
    rblState.DataValueField = "abbreviation";
    rblState.DataTextField = "name";
    rblState.DataBind();

}
like image 98
rick schott Avatar answered Dec 23 '22 18:12

rick schott


Try putting your populating codes in

if (!Page.IsPostBack)
{
    //your code here
}
like image 34
Kemal Can Kara Avatar answered Dec 23 '22 19:12

Kemal Can Kara