Implementar el evento CurrentRowChanged del DataGrid

2047 vistas

La clase DataGrid sólo tiene de forma nativa el evento CurrentCellChanged para indicar un cambio de celda. Por lo tanto, sólo tendremos que comparar la celda con una variable privada que represente la línea anteriormente seleccionada.

De esta manera podemos declarar un nuevo evento que al que llamaremos CurrentRowChanged.

Implementaremos una nueva clase (MiDataGrid) derivada de DataGrid capaz de disparar un evento CurrentRowChanged para indicar la línea en la que nos encontramos actualmente.



csharp
  1. using System;
  2. using System.Drawing;
  3. using System.Reflection;
  4. using System.Windows.Forms;
  5.  
  6. public class MiDataGrid : DataGrid
  7. {
  8.   public event EventHandler CurrentRowChanged;
  9.   public MonDataGrid(): base()
  10.   {
  11.       this.currentRowIndex = -1;
  12.   }
  13.   //...
  14.  
  15.   // acceso público que obtiene el Ãndice de la línea en curso
  16.   public int CurrentRow
  17.   { get{ return this.currentRowIndex;}}
  18.  
  19.   private int currentRowIndex;
  20.  
  21.   // sobrecarga del método base.OnCurrentCellChanged
  22.   protected override void OnCurrentCellChanged(EventArgs e)
  23.   {
  24.     base.OnCurrentCellChanged(e);
  25.     if(this.CurrentCell.RowNumber != this.currentRowIndex)
  26.     {
  27.       this.currentRowIndex = this.CurrentCell.RowNumber;
  28.       this.OnCurrentRowChanged(e);
  29.     }     
  30.   } 
  31.  
  32.   // disparo del evento CurrentRowChanged
  33.   protected virtual void OnCurrentRowChanged(EventArgs e)
  34.   {
  35.     if (this.CurrentRowChanged != null)
  36.     { this.CurrentRowChanged(this, e);}
  37.   }
  38.  
  39. }



Podemos usarlo de la siguiente manera:



csharp
  1. private void DataGrid1CurrentRowChanged(object sender, System.EventArgs e)
  2. {
  3.   MiDataGrid dg = (MiDataGrid)sender;
  4.   int rowindex = dg.CurrentRow;
  5.   if(rowindex == ((DataTable)dg.DataSource).Rows.Count)
  6.   { this.LComment.Text = "Estamos en la línea de inserción de registros";}
  7.   else
  8.   { this.LComment.Text = "línea " + rowindex.ToString();}
  9. }