SelectedIndex in DropdownList

  • Thread starter Thread starter Pascal
  • Start date Start date
P

Pascal

hi,

does anybody know how to set the selected index in a dropdownlist
when page is loaded for the first time? my code looks like:

int iCountryID = Int32.Parse(countryID);
dsCountryList = ds.getCountryList();
dropCountry.DataSource = dsCountryList;
dropCountry.DataValueField = "ID";
dropCountry.DataTextField = "Name";
dropCountry.DataBind();
dropCountry.SelectedIndex = iCountryID;

always first entry in dropdown is selected per default...

thx
pascal
 
Hi Pascal,

SelectedIndex should do the trick fine, I would check a couple of things:
1- iCountryID is parsed to a number different than 0
2- That you do not call DataBind again after that.


Cheers,
 
I'd do it like this:

Dim oListItem as ListItem
olistitem = dropCountry.items.FindByValue(iCountryID)
if not (olistitem is nothing) then
dropCountry.selectedItem.selected = false ' this if already have
a selected item.
olistitem.Selected = true
end if
 
The SelectedIndex is a 0-based number that specifies the literal index into the
list of items. So, the first item is index 0, second is 1, third is 2, etc.

If you are attempting to select based on some other identifier, you need to
find the physical index first. Use FindStringExact to lookup the name, or
iterate over the items looking for the appropriate country ID and then set that
item to selected.
 
Back
Top