Frederik Vig – ASP.NET developer

Follow me

ListControl AppendDataBoundItems and DataBind

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:

Share:
  • Twitter
  • DotNetKicks
  • DZone
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Digg

One Comment

  1. Martin S. says:

    Good tip! This way you don’t need to rebuild the dropdownlist on postback.

    This one might definitely come in handy.

Leave a Reply

Spam Protection by WP-SpamFree

© Copyright Frederik Vig. Based on Fluid Blue theme