如何基于DataGridView选中单元格值更新ComboBox的选中项?
解决方案
问题原因
当ComboBox完成数据源绑定后,控件的选中状态是和数据源条目强关联的,直接对Text属性赋值不会触发控件自动匹配数据源中的对应项,赋值会被控件的绑定逻辑忽略,所以看不到选中效果。
修复代码
把原来的SelectionChanged事件里的赋值逻辑替换成通过索引匹配的写法,示例如下:
Private Sub MyDataGridView_SelectionChanged2(sender As Object, e As EventArgs) Handles DataGridView2.SelectionChanged With DataGridView2 If .SelectedRows IsNot Nothing AndAlso .SelectedRows.Count = 1 Then Dim row As DataGridViewRow = .SelectedRows(0) ' 以下为ComboBox1的处理逻辑,剩余ComboBox2到ComboBox9对应修改单元格索引即可 If Not IsDBNull(row.Cells(5).Value) Then Dim targetArticulo As String = row.Cells(5).Value.ToString().Trim() Dim matchIndex As Integer = Form2.ComboBox1.FindStringExact(targetArticulo) If matchIndex <> -1 Then Form2.ComboBox1.SelectedIndex = matchIndex End If End If End If End With End Sub
额外注意事项
- 确认DataGridView对应单元格的值和ComboBox的
Articulo字段内容完全一致,避免大小写、特殊符号导致匹配失败,上述代码已经加了Trim()处理前后空格问题,如果需要忽略大小写可以改用FindString方法或者提前统一转大小写匹配 - 尽量不要直接使用VB的默认窗体实例
Form2,如果存在多个Form2实例的场景,建议传递已打开的Form2实例引用再操作控件 - 如果你的ComboBox同时设置了
ValueMember属性,也可以直接给SelectedValue赋值,运行效率会比查找索引更高
内容的提问来源于stack exchange,提问作者jumexmango
相关产品推荐
相关产品推荐

