How to set the default value of a data binding DropDownList easily with ASP.NET page

ASP.netThere 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 down

Me.dropdownExample.SelectedIndex = Me.dropdownExample.Items.IndexOf ( Me.dropdownExample.Items.FindByValue ( ‘The Default Value’ ) )
End Sub

You might be wondering why I bothered to use so long command to do so, and you might suggest the following way:

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!

  • Share/Bookmark
Tags: , ,

Related posts

2 Responses to “How to set the default value of a data binding DropDownList easily with ASP.NET page”


Leave a Reply



Get Adobe Flash playerPlugin by wpburn.com wordpress themes