Controlar un cambio de fila en un DataGrid (implementación de un nuevo evento, el CurrentRowChanged)
Artículo por Club Developers · 11 May 2006
2933 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.
Veamos cómo usarlo:
Implementaremos una nueva clase (MiDataGrid) derivada de DataGrid capaz de disparar un evento CurrentRowChanged para indicar la línea que tenga el foco.
vbnet
Option Explicit On Option Strict On Imports System Imports System.Drawing; Imports System.Reflection Imports System.Windows.Forms Public Class MiDataGrid Inherits DataGrid Public Event CurrentRowChanged As EventHandler Public Sub New() MyBase.New Me.currentRowIndex = -1 End Sub ' ... ' propiedad pública que obtiene el Ãndice de la lÃena actual Public ReadOnly Property CurrentRow() As Integer Get Return Me.currentRowIndex End Get End Property Private currentRowIndex As Integer ' sobrecarga del método MyBase.OnCurrentCellChanged Protected Overloads Overrides Sub OnCurrentCellChanged(ByVal e As EventArgs) MyBase.OnCurrentCellChanged(e) If Not (Me.CurrentCell.RowNumber = Me.currentRowIndex) Then Me.currentRowIndex = Me.CurrentCell.RowNumber Me.OnCurrentRowChanged(e) End If End Sub ' disparamos el evento CurrentRowChanged Protected Overridable Sub OnCurrentRowChanged(ByVal e As EventArgs) RaiseEvent CurrentRowChanged(Me, e) End Sub End Class
Veamos cómo usarlo:
vbnet
Private Sub DataGrid1CurrentRowChanged(ByVal sender As Object, ByVal e As EventArgs) Dim dg As MiDataGrid = CType(sender, MiDataGrid) Dim rowindex As Integer = dg.CurrentRow If rowindex = CType(dg.DataSource, DataTable).Rows.Count Then Me.LComment.Text = "Estás en la línea de addición de registro" Else : Me.LComment.Text = "línea " + rowindex.ToString() End If End Sub


