3
votes

I have a datagrid view that is bind to a custom collection. I have add remove options in the UI which will add and delete a row in datagridview.

Is there any way to get newly added rows in datagridview?

3
Do you want to know how to programaticaly add rows to the DGV or do you want to know how to get a reference to the newly added row?BFree
I want to know how to get a reference to the newly added row. Let's suppose my UI comes with some existing rows in data grid and User now add 2 new rows , I want to get the reference of those 2 rows only. I don't want to iterate all the rows in data grid viewAshish Ashu

3 Answers

6
votes

The DataGridView has a RowAdded event that gets triggered every time a Row is added (duh!). The Event args is of type: DataGridViewRowsAddedEventArgs which has a RowIndex property on it which enables you to do something like this:

    public Form1()
    {
        InitializeComponent();
        this.dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded);
    }

    private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
    {
        DataGridViewRow newRow = this.dataGridView1.Rows[e.RowIndex];
    }
1
votes

RowPrePaint event worked best to get the newly added row. I am using a databound datagridview.

private void dataGridView1_RowPrePaint(object sender, DataGridViewRowsAddedEventArgs e) 
    { 
        DataGridViewRow newRow = this.dataGridView1.Rows[e.RowIndex]; 
    }

The RowsAdded event didn't work for me. I am assuming, DataGridView doesn't add one row at a time or there is some other issue. The e.RowIndex in RowsAdded kept on returning 0 or 1.

0
votes

If the DataGridView is bound to a data source, the RowsAdded event is called only once for a range of rows. To get all the newly added rows you can use the e.RowIndex along with the e.RowCount as follow:

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    if (e.RowIndex == -1) return;

    for (int i = e.RowIndex; i < e.RowIndex + e.RowCount; i++)
    {
        DataGridViewRow newRow = this.dataGridView1.Rows[i];
    }
}