Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all,

I have a listbox which needed to fill data from database. How can I add more column into it? At my database i have tblCategory which has 2 column; ID and Category. When I add to my listbox with this 2 columns, it will insert as 1 index for each number followed by the Category in next. How can I get a row data and put in a single row in listbox but has many column? I have my code below that can load 1 column but not 2 column:

SQL
If rdr.HasRows Then
       While rdr.Read
                lbWhich.BeginUpdate()
                lbWhich.Items.Add(rdr.Item("ID"))
                lbWhich.Items.Add(rdr.Item("Category"))
                lbWhich.EndUpdate()
       End While
End If
Posted

Try this, I use it all the time

smodule is your sql connection string

VB
Using sqlCon = New SqlConnection(sModule)
            sqlCon.Open()
            Dim cmd As New SqlCommand("your sql query which returns two values ", sqlCon)
            cmd.ExecuteNonQuery()
            Dim adp As New SqlDataAdapter(cmd)
            Dim dt As New DataTable()
            adp.Fill(dt)
            lbWhich.DataSource = dt
            lbWhich.DataTextField = "Category"
            lbWhich.DataValueField = "ID"
            lbWhich.DataBind()
            sqlCon.Close()
        End Using



You use a datatable that has two column that you fill from the DB, and than assign a column to the value and text fields of the listbox, but it will only show the text to the user.

Let me know if it helps or works
 
Share this answer
 
v2
ListBox control can display only ONE data column. If you wish to display more than one data column you should try to use controls like ListView or DataGridView.

Here you have some informations:
http://www.dotnetperls.com/listview[^]
http://www.dotnetperls.com/datagridview-tutorial[^]

If you really need to use ListBox to display your data you can try to format strings while inserting data but still you will have only ONE column:
VB
lbWhich.Items.Add(String.Format("{0} - {1}", rdr.Item("ID"), rdr.Item("Category")))

More informations about string formatting you can find here:
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.format%28v=vs.110%29.aspx[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900