I've been working in a project with VS2005 and VB.NET, in this project I have a DataGridView with 3 DataGridViewComboboxCell inside of it. What I have been trying to do is make it so that when the user selects a value from the first DataGridViewComboboxCell the value of the 2 other cells change. This is the code for that part:
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
The first problem that I have is that when I open the list of the combobox and type I
to select one item of the combobox that start with I
. The combobox doesn't refresh to select this item and always goes back to the first item in the combobox, so what I do to make this work was change the value of the combobox on his own SelectedIndexChange like this:
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
The second problem is when I type another letter to select an item that starts with that letter and without pressing enter or clicking in the item that I changed to another DatagridViewComboboxCell the combobox that raises the SelectedIndexChanged event again which changes its value to the first item in the combobox.
Any idea why this happens?