I'm using a DataGridView and I bind a List to the DataSource.
I already have the right columns and I map exactly the fields. What I'm trying to do is handling a sort of RowAdded
or RowDataBound
(like in aspx GridView) event.
The only event that I found is RowsAdded
but no matter how many items I have, it is fired only 4 times the first time i bound, and twice the other times, with values
e.RowCount:1 e.RowIndex:0 e.RowCount:[n-1] e.RowIndex:1 *where n is the number of my items
is there a way I can get to a handle for each item?
EDIT: without changing the DataSource =
binding method
I just ran into this same issue. You can get the index and range of the rows that were added from the event args passed to the RowsAdded event handler. Use this information to loop through each of the added rows. e.RowIndex
and e.RowCount
will let you determine the added rows.
private void DataGridView1_RowsAdded(object sender, System.Windows.Forms.DataGridViewRowsAddedEventArgs e)
{
for (int index = e.RowIndex; index <= e.RowIndex + e.RowCount - 1; index++) {
DataGridViewRow row = DataGridView1.Rows[index];
// Do something with the added row here
// Raise a custom RowAdded event if you want that passes individual rows.
}
}
If you wanted you could inherit datagridview and make your own grid that throws a "RowAdded" event inside the loop above.
The easiest way for me is using a System.Windows.Forms.BindingSource. Add the list to that and then use the BindingSource as the grid DataSource. This then acts as a go-between for the grid and data.
There are then several events that can then be used from the bindingsouce. One of those is AddingNew. You can also use it to capture rows being add or removed, as well as several other things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With