Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databound drop down list - initial value

How do I set the initial value of a databound drop down list in ASP.NET?

For instance, I want the values, but the first value to display should be -- Select One ---, with a null value.

like image 967
mmcglynn Avatar asked Feb 06 '09 17:02

mmcglynn


People also ask

How to set initial value in DropDownList in asp net?

In the DataBound event of the dropdownlist, find the item either by text or value and set is as selected. You can do all this in the asp declarative code, without any VB or C# code behind.


2 Answers

I think what you want to do is this:

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">     <asp:ListItem Text="--Select One--" Value="" />    </asp:DropDownList> 

Make sure the 'AppendDataBoundItems' is set to true or else you will clear the '--Select One--' list item when you bind your data.

If you have the 'AutoPostBack' property of the drop down list set to true you will have to also set the 'CausesValidation' property to true then use a 'RequiredFieldValidator' to make sure the '--Select One--' option doesn't cause a postback.

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="DropDownList1"></asp:RequiredFieldValidator> 
like image 92
Phaedrus Avatar answered Sep 28 '22 05:09

Phaedrus


I know this is old, but a combination of these ideas leads to a very elegant solution:

Keep all the default property settings for the DropDownList (AppendDataBoundItems=false, Items empty). Then handle the DataBound event like this:

protected void dropdown_DataBound(object sender, EventArgs e) {     DropDownList list = sender as DropDownList;     if (list != null)         list.Items.Insert(0, "--Select One--"); } 

The icing on the cake is that this one handler can be shared by any number of DropDownList objects, or even put into a general-purpose utility library for all your projects.

like image 29
Matt L Avatar answered Sep 28 '22 03:09

Matt L