使用查询向我的组合框添加值

时间:2013-12-26 01:53:38

标签: vb.net vba

我正在尝试使用数据库中的信息填充我的组合框..但我不知道填充它的代码。顺便说一下,我正在使用vb windows窗体。

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

  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