Implementar el evento CurrentRowChanged del DataGrid
Artículo por Club Developers · 28 agosto 2006
2154 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.
Podemos usarlo de la siguiente manera:
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
using System; using System.Drawing; using System.Reflection; using System.Windows.Forms; public class MiDataGrid : DataGrid { public event EventHandler CurrentRowChanged; public MonDataGrid(): base() { this.currentRowIndex = -1; } //... // acceso público que obtiene el �ndice de la línea en curso public int CurrentRow { get{ return this.currentRowIndex;}} private int currentRowIndex; // sobrecarga del método base.OnCurrentCellChanged protected override void OnCurrentCellChanged(EventArgs e) { base.OnCurrentCellChanged(e); if(this.CurrentCell.RowNumber != this.currentRowIndex) { this.currentRowIndex = this.CurrentCell.RowNumber; this.OnCurrentRowChanged(e); } } // disparo del evento CurrentRowChanged protected virtual void OnCurrentRowChanged(EventArgs e) { if (this.CurrentRowChanged != null) { this.CurrentRowChanged(this, e);} } }
Podemos usarlo de la siguiente manera:
csharp
private void DataGrid1CurrentRowChanged(object sender, System.EventArgs e) { MiDataGrid dg = (MiDataGrid)sender; int rowindex = dg.CurrentRow; if(rowindex == ((DataTable)dg.DataSource).Rows.Count) { this.LComment.Text = "Estamos en la línea de inserción de registros";} else { this.LComment.Text = "línea " + rowindex.ToString();} }