Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a blank selection item to the list in drop down list

my dropdownlist is populated from the database as in:

DataTable dt = GetData(); ddlMylist.DataSource = dt; ddlMylist.DataBind();

Now dt contains the data, and I wish to add "Select" word to the top of the list when the selection is blank. It seems as there is no option other than add it to the dt (DataTable object)....but it seems wrong somehow.

What are other options. It's doesn't have to be the word "Select" it can be just an empty space...Currently, upon page load I can see the first data item in the list which is all good and dandy, but I have 3 drop downs that are co-dependent, and I want the user to explicitly make a selection which will trigger other drop downs to populate accordingly.

like image 1000
sarsnake Avatar asked Dec 14 '09 23:12

sarsnake


2 Answers

Try:

ddlMylist.Items.Insert(0, new ListItem([key], [text]));
ddlMylist.SelectedIndex = 0;

You do this after you databind to your source.

like image 180
Phil Sandler Avatar answered Oct 21 '22 05:10

Phil Sandler


Your dropdownlist markup should look like this:

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

Note the AppendDataBoundItems attribute.

like image 20
Joel Coehoorn Avatar answered Oct 21 '22 04:10

Joel Coehoorn