0

我正在尝试查看是否有更好的方法来使用返回 DataSet 的函数来填充组合框,或者更简洁的代码、更快的方法等。

功能:

    Public Function FillDataSet(ByVal dataSet As DataSet, ByVal queryString As String) As DataSet
      Using connection As New SqlConnection("Data Source=SQL;Initial Catalog=database; User ID=user;Password=password;")
         Using adapter As New SqlDataAdapter() With {.SelectCommand = New SqlCommand(queryString, connection)}
            adapter.Fill(DataSet)
         End Using
         Return DataSet
      End Using
    End Function

调用子:

    Private Sub fillComboBox()
      comboBox.Items.Clear()
      Dim myDataSet As New DataSet
      myDataSet = FillDataSet(myDataSet , "SELECT rows FROM table")
      If myDataSet .Tables(0).Rows.Count > 0 Then
        For Each row As DataRow In myDataSet .Tables(0).Rows
          comboBox.Items.Add(row(0))
        Next row
        comboBox.SelectedIndex = 0
      Else
        MsgBox("Empty table.", MsgBoxStyle.OkOnly, "Empty Table...")
      End If
      myDataSet .Dispose()
    End Sub
4

1 回答 1

2

将 for each 循环替换为comboBox.DataSource = myDataSet.Tables(0)然后分配要显示的列与其列名comboBox.DisplayMember = "ColumnName"和值成员以捕获其SelectedValue

comboBox.DataSource = myDataSet.Tables(0)
comboBox.DisplayMember = "ColumnName"
comboBox.ValueMember = "ColumnName"
于 2013-04-22T02:30:12.670 回答