Controlar un cambio de fila en un DataGrid (implementación de un nuevo evento, el CurrentRowChanged)

2326 vistas

La clase DataGrid sólo tiene de forma nativa el evento CurrentCellChanged para indicar el cambio de celda. Durante este evento, podemos comparar la línea a la que corresponde la celda con una propiedad privada que contenga la información de la línea anteriormente seleccionada. De esta manera podremos disparar un nuevo evento (al que llamaremos CurrentRowChanged) que nos indique un cambio de fila.

Implementaremos una nueva clase (MiDataGrid) derivada de DataGrid capaz de disparar un evento CurrentRowChanged para indicar la línea que tenga el foco.



vbnet
  1. Option Explicit On
  2. Option Strict On
  3.  
  4. Imports System
  5. Imports System.Drawing;
  6. Imports System.Reflection
  7. Imports System.Windows.Forms
  8.  
  9. Public Class MiDataGrid
  10.   Inherits DataGrid
  11.  
  12.   Public Event CurrentRowChanged As EventHandler
  13.   Public Sub New()
  14.   MyBase.New
  15.   Me.currentRowIndex = -1
  16.   End Sub
  17.   ' ...
  18.  
  19.   ' propiedad pública que obtiene el Ãndice de la lÃena actual
  20.   Public ReadOnly Property CurrentRow() As Integer
  21.     Get
  22.       Return Me.currentRowIndex
  23.     End Get
  24.   End Property 
  25.   Private currentRowIndex As Integer
  26.  
  27.   ' sobrecarga del método MyBase.OnCurrentCellChanged
  28.   Protected Overloads Overrides Sub OnCurrentCellChanged(ByVal e As EventArgs)
  29.     MyBase.OnCurrentCellChanged(e)
  30.     If Not (Me.CurrentCell.RowNumber = Me.currentRowIndex) Then
  31.       Me.currentRowIndex = Me.CurrentCell.RowNumber
  32.       Me.OnCurrentRowChanged(e)
  33.     End If
  34.   End Sub 
  35.  
  36.   ' disparamos el evento CurrentRowChanged
  37.   Protected Overridable Sub OnCurrentRowChanged(ByVal e As EventArgs)
  38.     RaiseEvent CurrentRowChanged(Me, e)
  39.   End Sub
  40. End Class



Veamos cómo usarlo:



vbnet
  1. Private Sub DataGrid1CurrentRowChanged(ByVal sender As Object, ByVal e As EventArgs)
  2.   Dim dg As MiDataGrid = CType(sender, MiDataGrid)
  3.   Dim rowindex As Integer = dg.CurrentRow
  4.   If rowindex = CType(dg.DataSource, DataTable).Rows.Count Then
  5.     Me.LComment.Text = "Estás en la línea de addición de registro"
  6.   Else : Me.LComment.Text = "línea " + rowindex.ToString()
  7.   End If
  8. End Sub