C# – How to check if any row is added to Datagridview

bindingsourcecdatagridview

I am using a Datagridview control on winform and a bindingsource for data. Data is filled in bindingsource and accordingly datagridview is populated. I am looking for an event or something like that which will fire up when a row from bindingsource is added to the datagridview.

I want to perform some operations over the added row. I tried with RowsAdded event but e.RowIndex is not being retrieved properly.

Edit1: Let's say I am having 10 records in database table. I am fetching these into bindingsource and using bindingsource as a datasource for Datagridview. Now while adding row to Datagridview, I want to perform some UI operations on the Datagridview. I used RowsAdded event but it is giving me RowIndex as 0 or 1 always. I also tried a foreach loop over RowsCount, and if I debug the code, the execution flow is as per the expectations, but on the UI it is not getting reflected. I have called Datagridview1.refresh() after everything is done.

Can you please help me out to get this ?

Best Answer

When the user adds a new row using the row for new records, the DataGridViewRowsAddedEventArgs.RowIndex value in the handler for this event is equal to the index of the new location of the row for new records, which is one greater than the row just added.

When you add rows programmatically, however, the RowIndex value is the index of the first row added.

private void dataGridView1_NewRowNeeded(object sender,
    DataGridViewRowEventArgs e)
{
    newRowNeeded = true;
}

private void dataGridView1_RowsAdded(object sender,
     DataGridViewRowsAddedEventArgs e)
{
    if (newRowNeeded)
    {
        newRowNeeded = false;
        numberOfRows = numberOfRows + 1;
    }
}

will fetch you the exact row refer msdn rowadded link

Related Topic