Blogs from
Welcome to Sign in | Join | Help
in Search

Ezequiel Espíndola's Blog

Selecting a default item after a DataBound operation in ASP.NET 2.0

When using the new DataSource objects you don’t need to write code for data binding. Code like this is not needed anymore:

DropDownList1.DataSource = DataSet1;
DropDownList1.Items.FindByValue(Request.QueryString[“state”]).Selected = true;

You simply point the DataSourceID property of the DropDownList to a properly setup SqlDataSource or ObjectDataSource and voila! binding occurs behind scenes without need for code.

However, how do you solve what comes after the call to DataBind(), the line that selects a current default value and could previously been in the Page_Load event or DataBind overridden method?

The easy way to do it is to define a handler for the OnDataBound event that gets fired after the control has been databound.

<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="Name" DataValueField="Id" OnDataBound="DropDownList1_DataBound" />

protected void DropDownList1_DataBound(object sender, EventArgs e)
  string selectedValue = Request.QueryString["id"];
  if (selectedValue != null)
    ListItem li = DropDownList1.Items.FindByValue(selectedValue);
    if (li != null)
      li.Selected = true;

This simple code checks to see if a value has been passed through the QueryString and that it actually exists on the ListItemCollection of the DropDownList. If everything goes fine, the item for the value passed will be selected.

Another related and interesting new feature of the controls derived from ListControl is the property “AppendDataBoundItems”.

In ASP.NET 1.x the DataBind operation always replaced the existing items, so you would have to bind items first and then add any custom values. You couldn’t specify them in a declarative way with an <asp:ListItem> tag on the page markup, but needed to add them programmatically. Now, if you set AppendDataBoundItems=”true” the existing items are kept in the collection.

Published Tuesday, February 21, 2006 1:18 PM by eespindola
Filed Under:
Anonymous comments are disabled

This Blog

Post Calendar

<February 2006>


Powered by Community Server, by Telligent Systems