Binding to a Listbox and Creating a Default ListItem

This demo illustrates how to bind a DataReader to a listbox Web control and how to add a "Choose an Option"-type listitem to the listbox. The results can be seen below. For more information on performing databinding with a listbox Web control be sure to read: Creating Databound DropDown Lists in ASP.NET.


FAQs at ASPFAQs.com:


Source Code
<% @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>:
  <form runat="server">
    <asp:listbox id="lstFAQs" runat="server" Rows="1" 
               DataTextField="Description" DataValueField="FAQID" />
  </form>
	


[Return to the article] | [Read Creating Databound DropDown Lists in ASP.NET]