【VB.NET】DataGridView上で範囲選択したセルの情報を取得する

画面イメージ

セル上でマウスボタンを押したとき、位置情報を保持する

VB
 Private Sub DataGridView1_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown

     'ヘッダの場合、スキップ
     If e.ColumnIndex < 0 Then Return
     If e.RowIndex < 0 Then Return

     '位置情報を保持
     CurrentPoint.StartRow = e.RowIndex
     CurrentPoint.StartColumn = e.ColumnIndex

 End Sub

セル上でマウスボタンを離したとき、選択範囲のセル合計値を算出し、ラベルに表示する

VB
  Private Sub DataGridView1_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseUp

      'ヘッダの場合、スキップ
      If e.ColumnIndex < 0 Then Return
      If e.RowIndex < 0 Then Return

      '位置情報を保持
      CurrentPoint.EndRow = e.RowIndex
      CurrentPoint.EndColumn = e.ColumnIndex

      '下から上、右から左への選択に対応するため、開始点・終了点の大小を把握する
      Dim SmallerX As Integer
      Dim BiggerX As Integer
      Dim SmallerY As Integer
      Dim BiggerY As Integer
      If CurrentPoint.StartRow < CurrentPoint.EndRow Then
          SmallerY = CurrentPoint.StartRow
          BiggerY = CurrentPoint.EndRow
      Else
          SmallerY = CurrentPoint.EndRow
          BiggerY = CurrentPoint.StartRow
      End If
      If CurrentPoint.StartColumn < CurrentPoint.EndColumn Then
          SmallerX = CurrentPoint.StartColumn
          BiggerX = CurrentPoint.EndColumn
      Else
          SmallerX = CurrentPoint.EndColumn
          BiggerX = CurrentPoint.StartColumn
      End If

      '選択範囲の合計値を産出
      Dim Sum As Integer = 0
      For Y = SmallerY To BiggerY
          For X = SmallerX To BiggerX
              Sum += DataGridView1(X, Y).Value
          Next
      Next

      lblSum.Text = Sum
  End Sub

動作確認用コード

VB
 Structure Coordinate
     Dim StartColumn As Integer
     Dim StartRow As Integer
     Dim EndColumn As Integer
     Dim EndRow As Integer
 End Structure

 Private CurrentPoint As Coordinate
 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

     Dim dt As New DataTable
     With dt
         .Columns.Add("Col1", GetType(String))
         .Columns.Add("Col2", GetType(String))
         .Columns.Add("Col3", GetType(String))
         .Columns.Add("Col4", GetType(String))
         .Columns.Add("Col5", GetType(String))
         .Columns.Add("Col6", GetType(String))
         .Rows.Add("1", "2", "3", "4", "5", "6")
         .Rows.Add("1", "2", "3", "4", "5", "6")
         .Rows.Add("1", "2", "3", "4", "5", "6")
         .Rows.Add("1", "2", "3", "4", "5", "6")
         .Rows.Add("1", "2", "3", "4", "5", "6")
         .Rows.Add("1", "2", "3", "4", "5", "6")
     End With

     With DataGridView1
         .DataSource = dt
     End With

 End Sub

コメント

タイトルとURLをコピーしました