views:

2162

answers:

3

Hi,

On my page I have a dropdownlist which gets populated by database values from an SqlDataSource(see code)

How can I add my own text or a blank line before the values...

<asp:DropDownList ID="drpClient" runat="server" Width="200px" 
                AutoPostBack="True" DataSourceID="dsClients" DataTextField="name" 
                DataValueField="client_id">
            </asp:DropDownList>
            <asp:SqlDataSource ID="dsClients" runat="server" 
                ConnectionString="my_connection_string" 
                ProviderName="System.Data.SqlClient" 
                SelectCommand="SELECT [client_id], [name] FROM [clients]">
            </asp:SqlDataSource>

Thanks,

P.s Is using SqlDataSources recommended or is it better to populate another way?

+6  A: 
<asp:DropDownList ID="drpClient" runat="server" Width="200px" 
        AutoPostBack="True" DataSourceID="dsClients" DataTextField="name" 
        DataValueField="client_id" AppendDataBoundItems="True">

    <asp:ListItem Text="" Value="" />
 </asp:DropDownList>

It's easy to miss, so don't forget the AppendDataBoundItems attribute I added.

Joel Coehoorn
+5  A: 

You can simply add a ListItem inside the DropDownList Markup. All the values from the DataSource will be appended after that.

<asp:DropDownList ID="drpClient" runat="server" Width="200px" 
          AutoPostBack="True" DataSourceID="dsClients" DataTextField="name" 
          DataValueField="client_id" AppendDataBoundItems="true">
   <asp:ListItem>-- pick one --</asp:ListItem>
</asp:DropDownList>
Jose Basilio
You have to tell it to 'append' rather than 'replace'
Joel Coehoorn
As you said, it's easy to miss :-)
Jose Basilio
thanks guys......
thegunner
+2  A: 

I haven't really tested this but I'm assuming that you could add an item after you have binded the the drop down list. You could add this event to any dropdown list you'd like to add this empty box to.

protected void DropDownList_DataBound(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        ListItem emptyItem = new ListItem("", "");
        ddl.Items.Insert(0, emptyItem);
    }
Justin Balvanz