2013-04-22 70 views
0

我想看看是否有使用返回數據集,以填補一個組合框,或者一個更乾淨的代碼,更快的方式等功能更好的方式VB.NET數據集功能

功能:

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 

回答

1

更換用於與comboBox.DataSource = myDataSet.Tables(0)每個環路然後分配與它的列名comboBox.DisplayMember = "ColumnName"和值構件dispaly哪一列用於捕獲其SelectedValue

comboBox.DataSource = myDataSet.Tables(0) 
comboBox.DisplayMember = "ColumnName" 
comboBox.ValueMember = "ColumnName" 
+0

感謝您的建議。 – RicEspn 2013-04-23 14:02:03