Thursday, July 5, 2007

AppendDataBoundItems property of Drop Down List box

AppendDataBoundItems property of Drop Down List box

Situation: For a drop down list box (combo box), if you want to have the default item to be shown as something like "(select from the list)", you can do it easily with this "AppendDataBoundItems" property.

Procedure:
- Drag and drop the drop down list box onto the "design" part of the .aspx page
- Do the binding stuff (from a dataset or whatever) in the code behind page (.aspx.cs)
- Open the "Source" part of the .aspx page. Scroll to the drop down list box's tag. Add the following code:

NOTE: I am removing the "<" and ">" tags because they are not rendered.

"asp:DropDownList ID="regddl" runat="server" Width="480px" Font-Size="9pt" ForeColor="SteelBlue" Visible="False" AppendDataBoundItems="True">
asp:ListItem Text ="(Select a usage type)" Value = ""> /asp:ListItem>
/asp:DropDownList>"


- The "Text" property of list item is displayed in the ddl box by default. Its value is null.
- You can have a RequiredFieldValidator to validate this ddl box so as to make sure, the user has made a valid selection (neither ignored selection nor selected default comment "select from list"), like this:

"asp:RequiredFieldValidator ID="rfvUsage" runat="server" ControlToValidate="regddl"
EnableViewState="False" ErrorMessage="Usage type required." Width="164px">** Usage type required. asp:RequiredFieldValidator>"

- All the above code can save lot of server side scripting.

Additional blogs which describe the above process are:

http://weblogs.asp.net/scottgu/archive/2006/01/29/436804.aspx
http://geekswithblogs.net/chrishan/category/2134.aspx/rss

Hope this was useful.

Thanks,
Shiva


Add to Technorati Favorites

1 comment:

Anonymous said...

Well said.