Results 1 to 2 of 2

Thread: Databinding to a listbox

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Feb 2002
    Posts
    98

    Databinding to a listbox

    This was so easy in classic asp and VB6, now I'm struggling.

    I have a asp.net form with a listbox, when the page loads I want a list of names from a table to fill the listbox.

    I'm using an Access database.

    I'm open to an early or late binding solution.

    I can't wait for the learning curve to pass on the .net
    G

  2. #2
    Hyperactive Member MarkusJ_NZ's Avatar
    Join Date
    Jun 2001
    Posts
    375
    Hi, this is totally off the top of my head so excuse any errors but should put you on the right path.

    There are a number of ways to do this here's one

    VB Code:
    1. ' Database connection object
    2. Dim oConn as new oledb.oledbconnection("Connectionstring")
    3. oConn.open
    4.  
    5. ' DataAdapter to get the information out of the database
    6. Dim oDA as new DataAdapter("SELECT UserName, UserID FROM Users",oConn)
    7. ' Dataset used to store the data retrieved from the database
    8. Dim oDS as new DataSet
    9. ' Fill the dataset with info from the database
    10. oDA.Fill(oDS)
    11.  
    12. ' Set your listbox datasource to the dataset
    13. MyListBox1.DataSource = oDS
    14. ' Set the text values (The values that the will appear in the listbox)
    15. MyListBox1.DataTextMember = "UserName"
    16. ' Set the vallue values (The values that are associated with the text items that appear in the listbox)
    17. MyListBox1.DataValueMember = "UserID"
    18. ' Bind the listbox to the datasource
    19. MyListBox1.DataBind()

    Hope this helps you out. You could also populate the listbox much like you would have using classic ASP using the DataReader object. The DataReader can be thought of as a foward only recordset object like the one available in classic ADO

    VB Code:
    1. ' open the connection
    2. ' Command object
    3.  
    4. Dim oCommand as new oledb.oledbCommand("SELECT UserName, UserID FROM Users",oConn)
    5. Dim oDR as New DataReader
    6. oDR = oCommand.ExecuteReader()
    7.  
    8. While oDR.Read
    9. ' Populate the datalist item much like you did in classic ASP
    10. MyListBox1.Add(oDR("UserName"))
    11. End While


    I usually code in SQL server so the Access bizzo (oledb) might not be right
    Cheers
    MarkusJ

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width