Bilal Haidar recently did a nice blog post that called out a small but useful new feature on the ListControl base class (which is the base control for a variety of input controls) in ASP.NET 2.0. Specifically it is a property called "AppendDataBoundItems", and it controls whether the items within an existing list are replaced or appended-to when the control is databound (with ASP.NET 1.1 the items were always replaced).
Here is a simple example of where this comes in handy:
<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource1" DataTextField="state" DataValueField="state">
<asp:ListItem Text="(Select a State)" Value="" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"
SelectCommand="SELECT DISTINCT [state] FROM [authors]">
In the above code I'm databinding the unique list of states in the pubs:authors table to an <asp:dropdownlist> control. For convenience sake I'm using the SqlDataSource control todo this -- although I could alternatively use either the ObjectDataSource to bind it against a class or just manually write code against the control's DataSource property.
What is new in ASP.NET 2.0 is that I can also specify some additional drop-down values -- such as an initial "(Select a State)" value -- that are not part of the databound result. Because the "AppendDataBoundItems" property is set to true, after databinding I will then have a dropdownlist whose first value is "(Select a State)" -- followed by the unique states currently in the authors table.
If I wanted to add validation, I could optionally then use a <asp:requiredfieldvalidator> control to point at the <asp:dropdownlist>:
ErrorMessage="Please select a state"
This would then output an error message "Please select a state" if the user tried to submit without choosing something other than the default "(Select a State)" item. Making them choose a non-default value this way forces them to make a concious choice as to which item to pick.
Special thanks to Bilal for calling out this new feature (I actually didn't know it existed until I read it a few minutes ago <g>),