Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting rows in datagridview using c#

Tags:

c#

I used following code to count datagrid rows, but it works on button only. I want the total number of rows in a textbox, but it doesn't increment itself as the number of rows increase.

int numRows = dataGridView1.Rows.Count;

txtTotalItem.Text = numRows.ToString();
like image 537
Rana Rashid Avatar asked Sep 05 '25 03:09

Rana Rashid


1 Answers

When you assign the number, the textbox will display only that number, it will not update.

You can use an event and assign the new number to the textbox.

dataGridView1.RowsAdded+=(s,a)=>OnRowNumberChanged;

private void OnRowNumberChanged()
{
    txtTotalItem.Text = dataGridView1.Rows.Count.ToString();
}

Following Equalsk's answer, you need to have the event for removed rows as well. You can subscribe to both events with the same function since you need to just check the number.

dataGridView1.RowsRemoved+=(s,a)=>OnRowNumberChanged();
like image 56
Mihai-Daniel Virna Avatar answered Sep 08 '25 00:09

Mihai-Daniel Virna