Add Default Value in DropDownList using ASP.NET 2.0
So we have a DropDownList in ASP.NET. The cool thing is, the framework gurus have made life a lot easier on us programmers in 2.0 in that the asp:DropDownList control and its cooresponding SqlDataSource control are side-by-side in design mode allowing you to wire up your DropDownList without ever touching the codebehind. It does beg the question of how to fill the default value though. Say you have some sort of personnel application, you don’t always want to default the option to Angela just because she’s numero uno in the list. We need to slide in a placeholder prior to the first name that prompts the user for action like “-Select an Employee-”. This is very easy. In the Page_Load event we are going to put the following:
Take particular notice of that last line. The AppendDataBoundItems allows the new default item to be included when we tack on the DataSource. Also note that this block needs to be wrapped in between a if (!IsPostBack) conditional to ensure that we don’t erase our user’s selection when we go to process out the selections.
For those interested in how we would have done this in ASP.NET 1.0, its basically this line of code that would come directly after the DataBind statement.
