■No35626に返信(HKaneさんの記事)
> 1行のみ、または、連続行選択のみを許し、> 例えば10行あるデータで2行目と5行目のみの選択のような歯抜け選択を許さないようにする方法はあるでしょうか?
泥臭い方法しか思いつきませんでした。
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.AllowUserToAddRows = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
DataGridView1.ColumnCount = 10
DataGridView1.RowCount = 1000
End Sub
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
Dim selectedRows = DataGridView1.SelectedRows.OfType(Of DataGridViewRow)().ToArray()
Dim firstRow = selectedRows.FirstOrDefault()
Dim lastRow = selectedRows.LastOrDefault()
If If(firstRow, lastRow) Is Nothing Then
Return
End If
Dim firstRowIndex = selectedRows.Min(Function(r) r.Index)
Dim lastRowIndex = selectedRows.Max(Function(r) r.Index)
If selectedRows.Length < (lastRowIndex - firstRowIndex) + 1 Then
Dim unselectedRows = DataGridView1.Rows.Cast(Of DataGridViewRow)() _
.Skip(firstRowIndex) _
.Take(lastRowIndex - firstRowIndex + 1) _
.Where(Function(r) Not r.Selected) _
.ToArray()
For Each row In unselectedRows
row.Selected = True
Next
End If
End Sub
End Class