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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With