VB ComboBox 的 listindex 自动变-1的问题
一个combobox控件 名为 cboCompany
相关代码如下
Private Sub cboLine_KeyPress(KeyAscii As Integer)
If KeyAscii < 48 Or KeyAscii > 57 Then
If KeyAscii <> 8 Then
KeyAscii = 0
End If
End If
End Sub
Private Sub cboCompany_Change()
Dim i As Integer
cboBus.Clear
If Len(Trim(cboCompany.Text)) = 3 Then
For i = 0 To cboCompany.ListCount - 1
'判断输入的数字 是否 与列表前几位数字相等
If CInt(Trim(cboCompany.Text)) = CInt(Mid(cboCompany.List(i), 1, Len(cboCompany.List(i)) - 2)) Then
cboCompany.ListIndex = i
Exit Sub
End If
Next
End If
End Sub
Private Sub cboCompany_Click()
Dim i As Integer
Dim sqlBus As String
''车辆
If cboCompany.ListIndex > -1 Then
cboBus.Clear
sqlBus = "Select bus_id,bus_no From zy_bus_info where company_no = '" & cboCompany.ItemData(cboCompany.ListIndex) & "' Order By cast(bus_no as int)"
Set rsForDeviceout = GetRSs(sqlBus, 0)
If rsForDeviceout.RecordCount > 0 Then
For i = 0 To rsForDeviceout.RecordCount - 1
cboBus.List(i) = Trim(rsForDeviceout!BUS_id)
cboBus.ItemData(i) = CStr(rsForDeviceout!BUS_NO)
rsForDeviceout.MoveNext
Next i
Else
'MsgBox "没有车辆信息,请设置!", vbInformation, "提示信息"
Exit Sub
End If
cboBus.ListIndex = -1
End If
End Sub
现在想实现 在组合框里输入3位数字 (此时触发change事件), 当 数字与列表中某项吻合时 cboCompany.ListIndex = i,不妨把i值定为8 即cboCompany.ListIndex = 8
,此时触发click事件 刷新另一个组合框
我跟踪了一下, click这里 cboCompany.ListIndex 是 8,刷新另一个框也没问题
后来下面点击按钮要保存数据时,cboCompany.ListIndex = -1 了,这时cboCompany.text是正确的值
不知道是怎么会变成-1
[解决办法]
默认的cboCompany.ListIndex = -1的吧 因为默认显示的第一行数据
我的理解
[解决办法]
简单点,既然cboCompany.text是正确的,那么你只需将下面这一段加到你要保存时点的那个按钮事件里面取一下index
If Len(Trim(cboCompany.Text)) = 3 Then
For i = 0 To cboCompany.ListCount - 1
'判断输入的数字 是否 与列表前几位数字相等
If CInt(Trim(cboCompany.Text)) = CInt(Mid(cboCompany.List(i), 1, Len(cboCompany.List(i)) - 2)) Then
'debug.print i '再取一下
Exit for
End If
Next
End If
[解决办法]
这跟控件无关,当你单击按钮时,Combo1会失去焦点,没有选中,combo1.listindex当然为-1了。
[解决办法]
ComboBox控件,
当控件未输入内容或输入的内容与ComboBox中选择项不匹配时,LinstIndex值就是-1