ASP.NET Code
  Home arrow ASP.NET Code arrow Page 4 - How to Use the ListBox Control in ASP.NET ...
Iron Speed
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Download TestComplete 
Windows Web Hosting
 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET CODE

How to Use the ListBox Control in ASP.NET 2.0
By: Jayaram Krishnaswamy
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 57
    2007-02-27

    Table of Contents:
  • How to Use the ListBox Control in ASP.NET 2.0
  • Usage of the ListBox Control in web pages
  • ListBox Examples
  • Dynamic binding to data at run time
  • Databound ListBox Example
  • Steps in converting a Unbound ListBox to a Bound ListBox

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    Iron Speed
     
    ADVERTISEMENT

    Ajax Application Generator Generate database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    How to Use the ListBox Control in ASP.NET 2.0 - Dynamic binding to data at run time
    (Page 4 of 6 )

    There are two ways you can populate the list with backend data. Well, not exactly two ways so much as two procedures using  the same AccessDataSource Control.

    Example 1: The Long hand

    The first of these is a roundabout way of getting the result. It still uses the AccessDataSource control by starting off using its connectionString as shown in the following (litany?) snippet. This was how data was accessed using ADO.NET 1.0.

    Imports System.Data.OleDb
    Partial Class _Default
       Inherits System.Web.UI.Page

       Protected Sub Button1_Click(ByVal sender As Object, _
       ByVal e As System.EventArgs) Handles Button1.Click
         Dim ds As New AccessDataSource
         ds = AccessDataSource1
         Response.Write(ds.ConnectionString)
         Dim mycon As New OleDbConnection
         Dim conStr As String = ds.ConnectionString
         mycon.ConnectionString = conStr
         mycon.Open()
         Response.Write("<h2>" & mycon.State & "</h2>")
         Dim myCmd As New OleDbCommand
         myCmd.Connection = mycon
         myCmd.CommandType = Data.CommandType.Text
         myCmd.CommandText = ds.SelectCommand.ToString
         Try
           Dim dr As OleDbDataReader = myCmd.ExecuteReader
           Response.Write(dr.HasRows)
           'Dim str As String = "" 
           While dr.Read
             ListBox1.Items.Add(dr.Item("CustomerID") & _
             "," & dr.Item("CompanyName") & "," & _
                               dr.Item("LastName") & "," & _
                                dr.Item("City") & "," _
                                & dr.Item("HomePhone"))
             'Response.Write(str)
           End While
           dr.Close()
         Catch ex As System.Data.OleDb.OleDbException
           Response.Write(ex.Message)
         End Try

         mycon.Close()

       End Sub
    End Class

    You may recall that this code is similar to what was formerly used in the VS2003 and described in a previously referenced article. The Design pane of this page (Default.aspx) is shown in the next picture followed by the source code listing of the page. In the source code make sure that the SelectCommand is all in one line. It should work as is except that the VS2005 IDE editor may emit some errors (it will work in spite of the emitted HTML error).

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server"> 
       <title>Longwinded</title>
    </head>
    <body>
       <form id="form1" runat="server">
       <div id="DIV1" runat="server"> 
         <asp:ListBox ID="ListBox1" runat="server"
         AppendDataBoundItems="True" AutoPostBack="false"
         Height="172px" Width="650px" >

         </asp:ListBox><asp:AccessDataSource
           ID="AccessDataSource1" runat="server"
           DataFile="~/App_Data/nwind.mdb" 
           SelectCommand="SELECT Customers.CustomerID,
           Customers.CompanyName, Customers.ContactName,
           Employees.LastName, Employees.City, Employees.HomePhone,
           Orders.OrderDate
           FROM ((Customers INNER JOIN Orders ON
           Customers.CustomerID = Orders.CustomerID)
           INNER JOIN Employees ON
           Orders.EmployeeID = Employees.EmployeeID)
           WHERE (Orders.OrderDate > #5/1/1998#)"

           </asp:AccessDataSource> 
         <asp:Button ID="Button1" runat="server"
    Text="Button" /></div>
       </form> 
    </body>
    </html>

    Example 2: Using DataSource directly

    The code behind shown for this CodeBound.aspx is simple and effortless  thanks to the ADO.NET 2.0 DataSource controls. Some of the AccessDataSource controls' properties are used.  The source code listing is also simpler as shown. The design pane of this example is exactly the same as in the previous example (Default.aspx). For this example you add the ListBox to the design pane and attach the datasource; you can get drop-down hints for writing the code.

    First, the code behind the click event of the button.

    Imports System.Data.OleDb
    Partial Class CodeBound
       Inherits System.Web.UI.Page

       Protected Sub Button1_Click(ByVal sender As Object, _
       ByVal e As System.EventArgs) Handles Button1.Click
         Dim ds As New AccessDataSource
         ds = AccessDataSource1
         Dim sqlstr As String = "Select * from Customers"
         ds.SelectCommand = sqlstr

         ListBox1.DataSource = ds
         ListBox1.DataValueField = "CustomerID"
         ListBox1.DataTextField = "CompanyName"
         ListBox1.DataBind()
       End Sub
    End Class

    The source code listing of CodeBound.aspx is much simpler than the previous case as shown below. Less code is the key word here.

    <%@ Page Language="VB" AutoEventWireup="false"
    CodeFile="CodeBound.aspx.vb" Inherits="CodeBound" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
       <title>Code Bound</title>
    </head>
    <body>
       <form id="form1" runat="server">
       <div>
         <asp:ListBox ID="ListBox1" runat="server" Height="177px"
    Width="333px">
         </asp:ListBox><asp:AccessDataSource
           ID="AccessDataSource1" runat="server"
           DataFile="~/App_Data/nwind.mdb" 
           SelectCommand="SELECT [CustomerID], [CompanyName],
                       [City], [Phone] FROM [Customers]">
         </asp:AccessDataSource>
         <br />
         <br />
         <asp:Button ID="Button1" runat="server"
    Text="Button" /></div>
        </form>
    </body>
    </html>

    This page gets rendered as shown in the next picture when the button is clicked.

    More ASP.NET Code Articles
    More By Jayaram Krishnaswamy


       · Declarative binding makes it very easy to work with databases even for those who are...
       · I am using the FormView control to create a form with a number of different type of...
       · Does the stored procedure work in the management studio correctly without...
     

    ASP.NET CODE ARTICLES

    - How to Use the ListBox Control in ASP.NET 2.0
    - How to Load XML Documents in ASP.NET 2.0
    - DataGrid Code
    - ASP.NET Guestbook
    - User Controls and Client Side Scripting
    - ASP.NET Programming with Microsoft's AS...
    - ASP.NET Basics (part 3): Hard Choices
    - ASP.NET Basics (part 2): Not My Type
    - ASP.NET Basics (part 1): Nothing But .Net
    - Directory Tree Browser
    - How to get the confirmation of Yes/No from a...
    - Complete example using custom errors and wri...
    - Paging Certain # records per page .NET style
    - General Methods of formatting and Subtractin...
    - .NET LinkButton web control

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway