by Pieter Brinkman
30. December 2008 04:41
I always have problems implementing the Asp.Net dropdown control. Here are some simple tips to make your life (with dropdown controls) easier.
Adding an default item with data binded dropdown
To add an default listItem to your data binded dropdown list you just have to add a ListItem on the first place (0) of your control
[code:c#]
CountryDropdown.DataSource = countryList;
CountryDropdown.DataValueField = "CountryId";
CountryDropdown.DataTextField = "CountryName";
CountryDropdown.DataBind();
//Add the item
CountryDropdown.Items.Inser(0, new ListItem("-- Choose a Country --"));
[/code]
Getting the selected value
[code:c#]
CountryDropdown.Items[CountryDropdown.SelectedIndex].Text;
[/code]
Setting dropdown listitem by value
[code:c#]
dropDownList.SelectedIndex = dropDownList.Items.IndexOf(dropDownList.Items.FindByValue(option.OptionValue));
[/code]
Validation on a dropdownlist
[code:c#]
<asp:RequiredFieldValidator id="reqGroupDDL"
Text="Choose group"
InitialValue="selectGroup"
ControlToValidate="GroupDDL"
Runat="server" />
[/code]
Hope it helps.