My problem was I wanted to multi select cells on a data grid view. I got that right and would like to post a solution here so it can maybe help someone else. My problem, however expanded from wanting to select 4 cells in one row to having to select cells in different rows and each time a person clicked a cell to select 4 consecutive cells and then to drag select a group of cells.
Well, this solution works for all three scenarios.
Dim rows As New List(Of Integer)
Try
For i As Integer = 1 To MyDataGridView.SelectedCells.Count
If Not rows.Contains(MyDataGridView.SelectedCells(i - 1).RowIndex) Then
rows.Add(MyDataGridView.SelectedCells(i - 1).RowIndex)
End If
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Try
For k As Integer = 1 To rows.Count
If MyDataGridView.Rows(rows(k - 1)).Cells(0 + 0).Selected = True _
Or MyDataGridView.Rows(rows(k - 1)).Cells(0 + 1).Selected = True _
Or MyDataGridView.Rows(rows(k - 1)).Cells(0 + 2).Selected = True _
Or MyDataGridView.Rows(rows(k - 1)).Cells(0 + 3).Selected = True _
Then
MyDataGridView.Rows(rows(k - 1)).Cells(0 + 0).Selected = False
MyDataGridView.Rows(rows(k - 1)).Cells(0 + 1).Selected = False
MyDataGridView.Rows(rows(k - 1)).Cells(0 + 2).Selected = False
MyDataGridView.Rows(rows(k - 1)).Cells(0 + 3).Selected = False
End If
For j As Integer = 4 To MyDataGridView.ColumnCount - 1 Step 6
Try
If MyDataGridView.Rows(rows(k - 1)).Cells(j + 0).Selected = True _
Or MyDataGridView.Rows(rows(k - 1)).Cells(j + 1).Selected = True _
Or MyDataGridView.Rows(rows(k - 1)).Cells(j + 2).Selected = True _
Or MyDataGridView.Rows(rows(k - 1)).Cells(j + 3).Selected = True _
Or MyDataGridView.Rows(rows(k - 1)).Cells(j + 4).Selected = True _
Or MyDataGridView.Rows(rows(k - 1)).Cells(j + 5).Selected = True _
Then
MyDataGridView.Rows(rows(k - 1)).Cells(j + 0).Selected = True
MyDataGridView.Rows(rows(k - 1)).Cells(j + 1).Selected = True
MyDataGridView.Rows(rows(k - 1)).Cells(j + 2).Selected = True
MyDataGridView.Rows(rows(k - 1)).Cells(j + 3).Selected = True
MyDataGridView.Rows(rows(k - 1)).Cells(j + 4).Selected = True
MyDataGridView.Rows(rows(k - 1)).Cells(j + 5).Selected = True
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Next
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Source: My boss.