Tuesday, 30 October 2007

ASP.NET DropDownList Appending Data Items

I am making a short post about this because I see so many questions and get asked so many times about this. When you have a databound DropDownList you will probably require an option which asks for the users selection.

A lot of the time people will use some code if not a postback and insert the items manually like so:


protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

ddlProfBody1.Items.Insert(0, new ListItem("Please Select", "0"));

}

}

BUT, I use the following to reduce code in the UI Layer:

<asp:DropDownList ID="ddlProfBody5" runat="server" DataSourceID="ProfBodyDS" DataTextField="Field1" DataValueField="Field0" AppendDataBoundItems="true">

<asp:ListItem Text="Please Select" Value="0">asp:ListItem>

:DropDownList>


What happens now is simply that instead of replacing any core items that were hardcoded, it does as the paramter suggests and appends additional items onto the drop downlist.