Published: Tuesday, July 31, 2001
Adding a Default ListItem in a Databound Listbox in ASP.NET
By Scott Mitchell
Introduction
In a previous article I showed how to use databinding to automagically
populate an ASP.NET's listbox Web control with just a few lines of code. (If you've not already read the
past article, be sure to do so now.) I've received a couple of
feedback emails from folks since publishing the article asking how to add a
default option to the listbox. That is, they want to add a listitem to the listbox, like: -- Please Choose
an Option Below--. In this brief article we'll tackle this topic and more!
Adding a ListItem to a Listbox Web Control
A listbox Web control contains zero to many listitem objects, each listitem representing an option
tag in the select form field that the listbox Web control ultimately renders. The listbox Web control
provides an Items property, which is an instance of the ListItemsCollection class. This class contains
methods for adding listitems to the collection, which in turn add new items to the listbox.
Therefore, to add a default option to a listbox, we must use one of these methods. But first, we should perform
our databinding. Databinding a DataReader (or DataSet) to the listbox populates the listbox with the database
information we specify in the listbox tag and the SQL query. (This topic was discussed at length in the
past article, Creating Databound DropDown Lists in ASP.NET.) Once we
successfully databind our database results to the listbox, we want to go ahead and smack a new listitem onto
the list.
So how to we add a new listitem to the listbox's Items property? We could use the Add
method of the ListItemCollection class, but this would stick the default option at the end of the listbox's list
of items. Fortunately the ListItemCollection class contains an Insert method, which allows us to
specify where in the ListItemCollection, exactly, we want to insert a new item.
The syntax for adding a new listitem to the ListItemCollection class via the Insert method is as
follows:
objListBox.Items.Insert(position, item)
|
where position is an integer specifying where in the ListItemCollection to add the listitem and
item is a ListItem class instance. Since the ListItemCollection is zero-based (as are all collections
and arrays in the .NET Framework classes), we want to specify position as 0; for
item we can create a new ListItem class instance with the value, --Select an Option-- (or
whatever we so please). When using the Insert method be sure to do it after you've already
done the databinding.
Below you will see the complete code for creating a databound listbox with a default option. There is also a
live demo that you should
be sure to check out.
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script language="vb" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
BindData()
End Sub
Sub BindData()
'1. Create a connection
Dim myConnection as New SqlConnection(ConfigurationSettings.AppSettings("connectionString"))
'2. Create the command object, passing in the SQL string
Const strSQL as String = "SELECT FAQID, LEFT(Description, 40) + '...' AS Description " & _
"FROM tblFAQ ORDER BY Description"
Dim myCommand as New SqlCommand(strSQL, myConnection)
'3. Create the DataReader
myConnection.Open()
Dim objDR as SqlDataReader
objDR = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
'Databind the DataReader to the listbox Web control
lstFAQs.DataSource = objDR
lstFAQs.DataBind()
'Add a new listitem to the beginning of the listitemcollection
lstFAQs.Items.Insert(0, new ListItem("-- Choose a FAQ --"))
End Sub
</script>
<b>FAQs at ASPFAQs.com</b>:
<asp:listbox id="lstFAQs" runat="server" Rows="1"
DataTextField="Description" DataValueField="FAQID" />
|
[
View the live demo!]
That's all there is to it!
Conclusion
This article showed how to add a default option to a databound listbox in ASP.NET, building upon a previous 4Guys
article: Creating Databound DropDown Lists in ASP.NET. All-in-all it's pretty
simple to do, just add one line of code after you've databound your listbox.
If you are using a default option like this, you might also want to use the RequiredFieldValidator to ensure that
the users are not choosing the default option; rather, that they are choosing one of the options that was
automatically populated when the listbox was databound. For more information on ASP.NET's validation controls, be sure
to read: Form Validation with ASP.NET - It Doesn't Get Any Easier!
Happy Programming!
By Scott Mitchell
Related Links
Read ASP.NET DropDownList Controls by Steve Smith
Read Dynamically Setting Text and Value Fields for a DropDownList Control