我正在尝试查看是否有更好的方法来使用返回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
答案 0 :(得分:1)
使用comboBox.DataSource = myDataSet.Tables(0)
替换每个循环,然后指定要显示的列,其列名为comboBox.DisplayMember = "ColumnName"
,值成员用于捕获其SelectedValue
comboBox.DataSource = myDataSet.Tables(0)
comboBox.DisplayMember = "ColumnName"
comboBox.ValueMember = "ColumnName"