listbox add items question

turrican

Freshman
Joined
Jan 24, 2003
Messages
27
Location
Phoenix, Az
I would now like to populate a list box on a win form from a data set. I will need to select two columns and combine them to display the first and last name of all of the people in my database so that the user can select the full name in the listbox.

I have another form with a datagrid. Is it possible to select a row on the datagrid to trigger an event?

I hope I worded all of this right.
 
you can use the Add method of the Listbox...
Visual Basic:
        Dim cn As New SqlConnection()
        Dim cmd As New SqlCommand()
        Dim dr As SqlDataReader

        cn.ConnectionString = "Data Source=127.0.0.1;Integrated Security=Yes;Initial Catalog=Northwind;Persist Security Info=False"

        cn.Open()
        Dim sSQL As String = "SELECT * FROM Orders order by CustomerID"

        cmd.Connection = cn
        cmd.CommandText = sSQL
        cmd.CommandType = CommandType.Text
        dr = cmd.ExecuteReader(CommandBehavior.Default)

        Do While dr.Read()
            ListBox1.Items.Add(dr("CustomerID") & " " & dr("OrderDate"))
        Loop
        dr.Close()
        cn.Close()

        cmd = Nothing
        dr = Nothing

Here's how you can bind the listbox...
The Value Member is usualy your Primary key.
Visual Basic:
        Dim ds As New DataSet()
        Dim sSQL As String = "SELECT CustomerID, (CompanyName + ', ' + Address) AS NewName FROM Customers order by CustomerID"

        Dim sConn As String = "Data Source=127.0.0.1;Integrated Security=Yes;Persist Security Info=False;Initial Catalog=Northwind;"
        Dim da As New SqlClient.SqlDataAdapter(sSQL, sConn)

        da.Fill(ds, "Orders")

        ListBox2.DataSource = ds.Tables(0)
        ListBox2.DisplayMember = "NewName"
        ListBox2.ValueMember = "CustomerID"
 
Last edited:
Back
Top