开发者

DataGridView row added event

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜