«
»

.NET, Programming, Visual Web Developer

ASP.NET: Adding a Null Row to a Data Bound Drop-Down List

07.10.06 | 20 Comments

Today’s .NET tip is a quickie (previous entries here and here): When you are using a database to fill the rows of a data bound drop-down list control, you will inevitably run into an error when the bound field is null or an empty string. You don’t want to add a null row to the list source, so what do you do?

This one’s simple – there’s a property of drop-down lists called AppendDataBoundItems. Set this to true, and you can provide one or more static entries, with rows from the list data source appened beneath them. Sample code:

<asp:DropDownList ID="BoundList"
runat="server"
DataSourceID="ListDataSource"
DataTextField="EntryDescription"
DataValueField="EntryID"
SelectedValue='<%# Bind("BoundItemID") %>'
AppendDataBoundItems="true">

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

</asp:DropDownList>

So, what we have here is a drop-down list called “BoundList”. This list gets its rows from a datasource called “ListDataSource”, displaying the value of “EntryDescription” while binding “EntryID” to the underlying field – which is called “BoundItemID”.

We then provide an empty list item to handle cases where no entry has been selected.

As always, please drop a note in the comments if this code helps you out.

20 Comments

have your say

Add your comment below, or trackback from your own site. Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

:

:


«
»