我一直在使用VS2005和VB.NET的项目中工作,在这个项目中,我有一个DataGridView,里面有3个DataGridViewComboboxCell。我一直试图做的是,当用户从第一个DataGridViewComboboxCell中选择一个值时,其他2个单元格的值会发生变化。这是该部分的代码:
Private Sub DataGridView1_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If (TypeOf e.Control Is DataGridViewComboBoxEditingControl) AndAlso _
DataGridView1.CurrentCell.ColumnIndex = 1 Then
Dim cbo As ComboBox = TryCast(e.Control, ComboBox)
If (cbo IsNot Nothing) Then
RemoveHandler cbo.SelectedIndexChanged, AddressOf comboBox_SelectedIndexChanged
AddHandler cbo.SelectedIndexChanged, AddressOf comboBox_SelectedIndexChanged
End If
End If
End Sub
Private Sub comboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim combo As ComboBox = TryCast(sender, ComboBox)
Dim rowIndex As Long = DataGridView1.CurrentRow.Index
Dim valueType As Type = GetType(Long)
If (combo.SelectedValue IsNot Nothing) Then
Dim comboValueType As Type = combo.SelectedValue.GetType()
Dim p As Boolean = valueType.Equals(comboValueType)
If Not valueType.Equals(comboValueType) Then
Exit Sub
End If
End If
DataGridView1.Rows(rowIndex).Cells(2).Value = 'Some DB query to retrieve the value
End Sub
我遇到的第一个问题是,当我打开组合框列表并输入I
时,选择以I
开头的组合框中的一个项目。组合框没有刷新来选择这个项目并且总是回到组合框中的第一个项目,所以我做的工作就是在他自己的SelectedIndexChange中更改组合框的值,如下所示:
Private Sub comboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim combo As ComboBox = TryCast(sender, ComboBox)
Dim rowIndex As Long = DataGridView1.CurrentRow.Index
Dim valueType As Type = GetType(Long)
If (combo.SelectedValue IsNot Nothing) Then
Dim comboValueType As Type = combo.SelectedValue.GetType()
Dim p As Boolean = valueType.Equals(comboValueType)
If Not valueType.Equals(comboValueType) Then
Exit Sub
End If
End If
DataGridView1.Rows(rowIndex).Cells(1).Value = combo.SelectedValue
DataGridView1.Rows(rowIndex).Cells(2).Value = 'Some DB query to retrieve the value
End Sub
第二个问题是,当我键入另一个字母来选择以该字母开头的项目而不按Enter或单击我更改为另一个DatagridViewComboboxCell的项目时,再次引发SelectedIndexChanged事件的组合框会将其值更改为组合框中的第一项。
知道为什么会这样吗?
答案 0 :(得分:1)
你很亲密。这就是我对selectedIndexChanged所做的更新。
我注意到问题似乎在于combo.SelectedValue行。除非您离开单元格,否则此值永远不会更改。您需要使用的是combo.SelectedItem,每次更改组合框时都会更改。
请改为尝试:
Private Sub comboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim combo As ComboBox = TryCast(sender, ComboBox)
Dim test As Long
If (combo.SelectedItem IsNot Nothing) Then
If Not Long.TryParse(combo.SelectedItem, test) Then
Exit Sub
End If
End If
DataGridView2.CurrentCell.Value = combo.SelectedItem
DataGridView1.Rows(rowIndex).Cells(1).Value = combo.SelectedItem
DataGridView1.Rows(rowIndex).Cells(2).Value = 'Some DB query to retrieve the value
我改变了你检查它是否很长的方式。如果它通过Long.TryParse那么它很长。这段代码可以让我改变其他Cell的值,如果这不能修复它,那么我不确定会是什么。我还将所有SelectedValue更改为SelectedItem,因为SelectedValue始终保持最后选择的值,而不是当前值。