VB.NET 数据集函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16138454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET DataSet Function
提问by RicEspn
I'm trying to see if there's a better way to use a function that returns a DataSet to fill a combo box, or a cleaner code, faster way, etc.
我想看看是否有更好的方法来使用返回 DataSet 来填充组合框的函数,或者更简洁的代码、更快的方法等。
Function:
功能:
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
Calling Sub:
呼叫子:
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
回答by Jon P
Replace the for each loop with comboBox.DataSource = myDataSet.Tables(0)then assign which column to dispaly with its column name comboBox.DisplayMember = "ColumnName"and value member for catching its SelectedValue
将 for each 循环替换为comboBox.DataSource = myDataSet.Tables(0)然后分配要显示的列及其列名comboBox.DisplayMember = "ColumnName"和值成员以捕获其SelectedValue
comboBox.DataSource = myDataSet.Tables(0)
comboBox.DisplayMember = "ColumnName"
comboBox.ValueMember = "ColumnName"

