Setting ASP.Net DropDownList Default Value
There are number of ways to set the Default value for ASP.Net DropDownList control that allow you to display its list item appear as selected item by default. It depends upon your requirement to display which item dropdownlist control appear as default value. There are three types of situations to apply the same functionality with different ways for example you are inserting the data into the database, updating the data or selecting the data items from the database using ASP.Net web page. If you are using the web form to insert the data then you can display the default value of dropdownlist control using following code:
DropDownList1.Items.Insert(0, new ListItem("[Please select any item]", ""));
The above code will add a new list item at the top of items collection of DropDownList control and by default it will appear as selected item at the top.
DropDownList Control Examples:
You can see the live samples and examples of DropDownList Control from the following links:
The second type of situation occurs when you are updating the old data then you have to display the default value of DropDownList control as previously saved value in the database. You can use the following code to set the list item as default selected value for dropdownlist control:
DropDownList1.SelectedValue = "itemvalue";
The SelectedValue property of dropdownlist accepts the string value that will appear as select item.
The last type of situation occurs when you are fetching the data from database using a web form that has dropwdownlist control to specify a parameter for search query. For this type of cases you may need to display some specific default values already selected in the controls to refine the search filters. You can use any of the above C# code examples to set the default values. Following are some more C# code ideas for setting the selected list item of dropdownlist as default value:
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("Confections"));
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue("3"));
DropDownList1.Items.FindByValue("4").Selected = true;
It may vary for different types of situations that which code example suits to your requirement.
Continue to next tutorial: ASP.Net DropDownList SelectedValue Property to learn the use of SelectValue property of dropdownlist control.