user670186
user670186

Reputation: 2840

VB.NET datagrid - detect combo box selection and select same value in different column

I have a datagrid with combo boxes. Now I want to achieve that if on selects value x in column 0 row 0 then then combo box value y in colum 1 row 0 is set to the same value like x automatically.

I tried

 Private Sub dataGridView1_CellValidating(ByVal sender As Object, ByVal e As DataGridViewCellValidatingEventArgs) Handles Sched_Grid.CellValidating
    If Sched_Grid.CurrentCell.ColumnIndex = 0 Then
        Sched_Grid(1, Sched_Grid.CurrentCell.RowIndex).Value = Sched_Grid(0, Sched_Grid.CurrentCell.RowIndex).Value
    End If
End Sub

However, it doesnt work immediately. I have to first selected a value x(0,0), then click a different cell(5,5 or something else) and then click back into x(0,0) cell so that y(1,0) gets set to x(0,0).

How can this be solved?

Upvotes: 1

Views: 5785

Answers (2)

Holger Brandt
Holger Brandt

Reputation: 4354

You need to use the EditingControlShowing event to get to the underlying control and then add another handler. It gets a little messy though.

Private Sub Sched_Grid_EditingControlShowing(ByVal sender as Object, Byval e as DataGridViewEditingControlShowingEventArgs) Handles Sched_Grid.EditingControlShowing
  If Sched_Grid.CurrentCell.ColumnIndex = 0 Then
    Dim selectedComboBox As Combobox = DirectCast(e.Control, ComboBox)
    RemoveHandler selectedCombobox.SelectionChangeCommitted, AddressOf selectedComboBox_SelectionChangeCommitted
    AddHandler selectedCombobox.SelectionChangeCommitted, AddressOf selectedComboBox_SelectionChangeCommitted
  End If
End Sub

Private Sub selectedComboBox_SelectionChangeCommitted(ByVal sender As Object, ByVal e As EventArgs)
  Dim selectedCombobox As ComboBox = DirectCast(sender, ComboBox)
  If selectedCombobox.SelectedItem IsNot Nothing Then
    Sched_Grid(1, Sched_Grid.CurrentCell.RowIndex).Value = selectedCombobox.SelectedItem
  End If
End Sub

Upvotes: 2

Jeff B
Jeff B

Reputation: 8982

You might be able to the CurrencyManager class to bind both controls to the same collection. On the ComboBox you can use the DisplayMember property to display only the column you want.

Simple example: http://www.vb-tips.com/CurrencyManager.aspx

Upvotes: 0

Related Questions