Click to See Complete Forum and Search --> : Getting and settting values of combobox in web ap


Lars_V_J
August 17th, 2009, 02:37 AM
In my code, I use this to set the values of two combos:
CB_BCountry.Items.FindByValue(resp.GetPersonResult.BirthCountryIdentifier.ToString()).Selected = true;
CB_Nationality.Items.FindByValue(resp.GetPersonResult.PrimaryNationlityIdentifier.ToString()).Selected = true;

This happens in a button click function.

If, however, I try to get the value by using
System.Web.UI.WebControls.ListItem item1 = CB_BCountry.SelectedItem;
string s1 = item1.Value;
System.Web.UI.WebControls.ListItem item2 = CB_Nationality.SelectedItem;
string s2 = item2.Value;

in another button click function, I *always* get the first item, no matter selection. If I do it in the Page_Load function, I get an error about not being allowed to select more than one item in a combobox.
I am extremely confused. How the h...do I properly get and set my current selection?

Thank you in advance.

monalin
August 17th, 2009, 05:35 PM
To get the value of a selected item use this


// If no value selected s1 will just contain an empty string.
String s1 = CB_BCountry.SelectedValue;


To set the index you cannot set the ListItem.Selected to true if there is already an item selected. Thats why you're getting the error. The best way to do that is like this.


ListItem item = CB_BCountry.Items.FindByValue(resp.GetPersonResult.BirthCountryIdentifier);
CB_BCountry.SelectedIndex = CB_BCountry.Items.IndexOf(item);