There are a lot ways to set the default value for a dropdownlist when it has been databinded in an ASP.NET Page. I will list some of them and point out the pros and cons.
Way #1 (recommended way):
In an ASP.NET page, if the DropDownList web control (here I call dropdownExample) has an datasource (sqldatasource or objectdatasource), and when it is data binding you can define the following:
Protected Sub dropdownExample_DataBound(ByVal sender As Object,
ByVal e As System.EventArgs) Handles dropdownExample.DataBound
‘set the default value for the drop downMe.dropdownExample.SelectedIndex = Me.dropdownExample.Items.IndexOf ( Me.dropdownExample.Items.FindByValue ( ‘The Default Value’ ) )
End Sub
Way 2:
Everything is the same as the Way 1, only difference is the below:
dropdownExample.SelectedValue = “Default Value”
While it is a simple one, but actually it is replacing the selectedValue of the DropdownList.
Way 3:
Another suggestion will be:
dropdownExample.Items.FindByValue(“Default Value”).Selected = true
It will be working perfectly if the “Default Value” is in the list items collection. But if it is not, then the application will throw an “object is not an instance” exception error. Of course, you can always use Try…Catch block to avoid it. But still I do not recommend it either.
Way 4:
If you use the DropdownList web control in a FormView or other similar web control which has another Databinding, then you can SelectedValue attribute directly in DropDownList webcontrol tag. Like this:
<asp:DropDownList ID=”dropdownExample” runat=”server” DataSourceID=”ObjectDataSource_Dropdown” DataTextField=”NAME” DataValueField=”ID” AppendDataBoundItems=”True” selectedValue=”<%# Eval(‘AnotherValue’) %>”>
Happy Programming!
Tags: asp.net, dropdownlist, vb.net
These are terrible suggestions.
[Reply]
There is no property SelectedValue for the DropDownList control as suggested in “Way 4″.
[Reply]