当下拉列表样式设置为"下拉列表"时,如何使用默认值设置组合框



我正在使用Visual Studio 2019,我一直在尝试让我的组合框使用数据库中的记录设置默认值。 我将下拉列表样式设置为"下拉列表",这是我正在使用的代码。

首先,我将列表框从状态数据表加载到组合框中

Private Sub frmABS3_Shown(sender As Object, e As EventArgs) Handles Me.Shown
modABS.clsABS.ExecQuery("SELECT * FROM tblABSStates")
If Not String.IsNullOrEmpty(modABS.clsABS.Exception) Then MsgBox(modABS.clsABS.Exception) : Exit Sub
For Each r As DataRow In modABS.clsABS.DBDT.Rows
cboState.Items.Add(r("StateAbbrev"))
Next
End Sub

接下来,我将填充表单上的字段。 这是我遇到麻烦的部分。

Private Sub GetRecord()
' Fail if No Records Found or position is out of Range
If modABS.clsABS.DBDT.Rows.Count < 1 OrElse CurrentRecord > modABS.clsABS.DBDT.Rows.Count - 1 Then Exit Sub
'Return first user found
Dim r As DataRow = modABS.clsABS.DBDT.Rows(CurrentRecord)
'Populate Fields
cboState.Text = r("StateAbbrev").ToString
txtCity.Text = r("City").ToString
End Sub

当我运行代码时,组合框不显示状态缩写,并且未在列表中选择该项。 当我将下拉列表样式设置为"下拉列表"时,它的工作方式是假定的,但是我不希望用户能够添加组合列表框中没有的值。

此代码需要在表单加载事件中,而不是表单显示事件中:

Private Sub frmABS3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
modABS.clsABS.ExecQuery("SELECT * FROM tblABSStates")
If Not String.IsNullOrEmpty(modABS.clsABS.Exception) Then MsgBox(modABS.clsABS.Exception) : Exit Sub
For Each r As DataRow In modABS.clsABS.DBDT.Rows
cboState.Items.Add(r("StateAbbrev"))
Next
txtZipCode.Text = modABS.clsABS.ZipCode
End Sub

最新更新