简体   繁体   中英

adding a value to my combo box using query

I'm trying to populate my combo box using the information in my database.. but I don't know the code for populating it. btw, I'm using vb windows form.

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
    Dim con As SqlConnection = New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=Acounting;User ID=sa;Password=123")
    Dim cmd As SqlCommand = New SqlCommand("select distinct CompanyName from company ", con)
    cmd.ExecuteReader()
    con.Open()
    While cmd.ExecuteReader.Read
    End While
    con.Close()
End Sub
Private Sub Form1_Load(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles MyBase.Load
        Using cnn As New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=Acounting;User ID=sa;Password=123")
        Using Adp as new SqlDataAdapter("select distinct CompanyName from company", con)
            Dim Dt as New DataTable
            Adp.Fill(Dt)
            ComboBox1.DataSource=Dt
            ComboBox1.DisplayMember="CompanyName"
        End Using 
        End Using 
End Sub
  Using cnn As New SqlConnection("Data Source=PC11-PC\kim;Initial Catalog=Acounting;User ID=sa;Password=123")
    Using cmd As New SqlCommand("select distinct CompanyName from company", cnn)

    Try
      cnn.Open()
      Dim r = cmd.ExecuteReader

      If r.HasRows Then
        While r.Read
          ''add the items to the ComboBox
          ComboBox1.Items.Add(r.GetString(0))
        End While
      End If
    Catch ex As Exception
      ''handle the error
    End Try
  End Using
End Using

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM