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

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.

13 Comments »

  1. Comment by Anonymous

    Cheers. Exactly what I was looking for.

    Thanks again

  2. Comment by Anonymous

    Thanks man! I was really lost…

  3. Comment by Anonymous

    Exactly what I needed! Thanks for the post.

  4. Comment by Anonymous

    Thanks, very helpful

  5. Comment by rupa

    Hey it works, Thanks for posting .

  6. Comment by Ömür

    Thank you very much. That’s what i looked.
    That’s realy helpful.

  7. Comment by JB

    Thanks, this works nicely.

    Just remember that it is not enough to set {Text = “”, Value = “”} in DropDpwnList.Items editor as that will produce an item with no value; you’ll apparently need to add Value=”" manually to the page source.

  8. Comment by i have 4 dropdowns if i select 1& 3 dropdown then only enter into loop otherwise execute outerloop

    very good. i am satisfyed

  9. Comment by bill

    this helped a lot. I was going crazy trying to figure this out.

  10. Comment by milton

    Perfect. Concise and to the point. Thank you very much for posting this!

  11. Comment by Ashu

    Thank you so much. I spent a whole hour trying to make this work, but now realized that I was missing AppendDataBoundItems=”true” line.

  12. Comment by Zankar

    Thanks. It’s a Good Clue.

  13. Comment by kral oyun

    thanks

RSS feed for comments on this post. TrackBack URI

Leave a comment

If you want to leave a feedback to this post or to some other user´s comment, simply fill out the form below.

(required)

(required)