Combining Static and Dynamic Items in an ASP.NET ListControl


Say, for example, you have a DropDownList which contains a list of town names you pull from a DB and you want to add a wildcard option to match any town name. I've always hooked into the DataBound event of the DropDownList and added an extra item at the head of the list:

    protected void DropDownList1_DataBound(object sender, EventArgs e)
    {
      DropDownList1.Items.Insert(0, new ListItem("Any Town", "%"));
    }

Turns out that as of ASP.NET 2.0 a new property was added to ListControl that allows you to maintain the static list items through a databind, the net result being that static and dynamic items are combined. This makes life a lot easier. All I have to do is:

      <asp:DropDownList ID="DropDownList1" runat="server"
        AppendDataBoundItems="true">
        <asp:ListItem Text="Any Town" Value="%"></asp:ListItem>
      </asp:DropDownList>

I no longer have to hook an event or write any code. Where exactly was I when this information was handed out?

Technorati Tags: ,
Skip to main content