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?
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?
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];
}
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.
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];
}
}