Why is my DropDownList's SelectedItem not working?

心已入冬 提交于 2019-12-10 17:07:34

问题


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?


回答1:


You are probably re-binding the DataSource on PostBack.

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

}



回答2:


Try putting your populating codes in

if (!Page.IsPostBack)
{
    //your code here
}



回答3:


does your control have the runat="server" property set? That one's bitten us all at one point or another I'm sure.

Also I beleive you have to set your AutoPostBack="true" so it notifies the server when you change a list item. Otherwise I beleive you have to get it client side if it's not updating the server with the newly selected option.




回答4:


As with any variables, you should always check them before trying to call sub-properties.

Check SelectedIndex != -1 to make sure a value was selected OR check to make sure that SelectedItem != null.

Make sure that you are binding your DropDownList only on the page's first load (as Kemal stated).



来源:https://stackoverflow.com/questions/8343125/why-is-my-dropdownlists-selecteditem-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!