我有一个使用一组三个组合框的应用程序。 我已设法根据前一个下拉列表的选定值填充每个下拉列表 唯一的问题是,由于数据来自数据库,来自第一个组合框的两个选定值可能在数据库中具有两个不同数量的项目。因此,每次调用第一个组合框的selectedIndex_changed nethod时,第二个组合框应填充此类数据
例如,如果第一个组合框的第一个项目在第二个组合框中有10个对应的项目,而第一个组合框的第二个项目在第二个组合框中有三个对应的项目,则在选择第一个项目后选择第二个项目将导致第二个组合框显示三个项目,七个空白项目落后于三个项目。
我想要的是当第一个组合框中的第二个项目在数据库中有三个项目时,第二个组合框完全加载了三个项目
这是一个例子
Private Sub cboAccountGroup_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboAccountGroup.SelectedIndexChanged
If mblnAccountGroupFirstLoad = True Then
Exit Sub
End If
Dim index As String
index = cboAccountGroup.SelectedValue
'Call clearDataEntries()
Dim psql As String
psql = "Select Account_Type_ID,Description from Tbl_Account_Type Where Account_Group_id=" & index
Call setDropDowns(cboAccountType, psql)
mblnAccountTypeFirstLoad = False
End Sub
setDropDowns定义如下
Public Sub setDropDowns(ByRef combo As ComboBox, ByVal sql As String)
Try
Dim adaptor As New SqlDataAdapter(sql, mcon)
Dim dataset As New DataTable()
mcon.Open()
adaptor.Fill(DataSet)
mcon.Close()
combo.DataSource = DataSet
combo.DisplayMember = DataSet.Columns(1).ColumnName
combo.ValueMember = DataSet.Columns(0).ColumnName
Catch ex As Exception
Finally
'mcon.Close()
End Try
End Sub
请协助。
答案 0 :(得分:1)
我会稍微改变代码看起来更像这样:
'Build functions that return data, and keep them separate from code that updates your UI
Public Function GetAccountTypesByAccountID(ByVal AccountGroupID As Integer) As DataTable
Dim sql As String = "SELECT Account_Type_ID,Description FROM Tbl_Account_Type Where Account_Group_id= @AccountGroupID"
Dim result As New DataTable()
'Create a new connection each time. Really! Thanks to connection pooling, this is the way to go
Using mcon As New SqlConnection(GetConnectionString()), _
cmd As New SqlCommand(sql, mcon)
'USE PARAMETERIZED QUERIES!!
cmd.Parameters.Add("@AccountGroupID", SqlDbTypes.Int).Value = AccountGroupID
'The Using block will make sure the connection is closed, even if an exception is thrown
mcon.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
result.Load(rdr)
End Using
End Using
Return result
End Function
Private Sub cboAccountGroup_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboAccountGroup.SelectedIndexChanged
If mblnAccountGroupFirstLoad Then Exit Sub
mblnAccountTypeFirstLoad = False
' clearDataEntries()
Dim AccountTypes As DataTable = GetAccountTypesByAccountID(Integer.Parse(cboAccountGroup.SelectedValue))
cboAccountType.DisplayMember = AccountTypes.Columns(1).ColumnName
cboAccountType.ValueMember = AccountTypes.Columns(0).ColumnName
cboAccountType.DataSource = AccountTypes 'Set datasoure LAST
End Sub