ListControl AppendDataBoundItems and DataBind

Posted on April 19, 2010 by Frederik Vig in ASP.NET

By default when using code like this, the list item will be cleared when data binding is performed.

<asp:DropDownList runat="server" ID="ddlCategories">
    <asp:ListItem>Please choose</asp:ListItem>
</asp:DropDownList>
protected override void OnLoad(EventArgs e)
{
	base.OnLoad(e);
 
	string[] categories = new[] { "C#", "ASP.NET", "EPiServer", "Umbraco", "jQuery" };
 
	ddlCategories.DataSource = categories;
	ddlCategories.DataBind();
}

Will give us.

 <select name="ctl00$MainContent$ddlCategories" id="MainContent_ddlCategories">
	<option value="C#">C#</option>
	<option value="ASP.NET">ASP.NET</option>
	<option value="EPiServer">EPiServer</option>
	<option value="Umbraco">Umbraco</option>
	<option value="jQuery">jQuery</option>
</select>

As you see “Please choose” is not there any more.

However if you set the AppendDataBoundItems property to true (default is false), the list items will be added before data binding is performed.

protected override void OnLoad(EventArgs e)
{
	base.OnLoad(e);
 
	...
	ddlCategories.AppendDataBoundItems = true;
	...
}

The markup is now correct.

<select name="ctl00$MainContent$ddlCategories" id="MainContent_ddlCategories">
	<option value="Please choose">Please choose</option>
	<option value="C#">C#</option>
	<option value="ASP.NET">ASP.NET</option>
	<option value="EPiServer">EPiServer</option>
	<option value="Umbraco">Umbraco</option>
	<option value="jQuery">jQuery</option>
</select>

Related Posts: