我有五个组合框,需要填充与每个组合框中插入的文本相关的项目。
我如何重用相同的函数以在DataTable中用不同的结果填充多个组合框?
Private Sub Search()
Dim adp As SqlDataAdapter = New SqlDataAdapter("select stage from sample where stage like '%" + ComboBox1.Text + "%'", connection)
Dim table As New DataTable
adp.Fill(table)
ComboBox1.DataSource = New BindingSource(table, Nothing)
ComboBox1.DisplayMember = "stage"
End Sub
Private Sub ComboBox1_PreviewKeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles ComboBox1.PreviewKeyDown
If e.KeyCode = Keys.Tab Then
Search()
End If
End Sub
创建一个类似这样的功能:
Public Sub BindComboBox(ByRef cboBox As ComboBox, ByVal sSQL As String, ByVal sFieldNameOfReturnValue As String, ByVal sFieldNameOfDisplayText As String)
Try
Dim adp As SqlDataAdapter = New SqlDataAdapter(sSQL, connection)
Dim dtAllData As New DataTable
adp.Fill(dtAllData)
Dim xBindingContext As New BindingContext
With cboBox
.BindingContext = xBindingContext
.DataSource = dtAllData
.ValueMember = sFieldNameOfReturnValue.ToUpper
.DisplayMember = sFieldNameOfDisplayText.ToUpper
End With
Catch Exp As Exception
'Handle exceptions here
End Try
End Sub
然后您将这样调用此函数:
Call BindComboBox(ComboBox1, "select stage from sample where stage like '%" + ComboBox1.Text + "%'", "stage", "stage")
Call BindComboBox(cboCompanies, "SELECT CompanyID, CompanyName, FROM Companies", "CompanyID", "CompanyName")