Reputation: 129
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();
Upvotes: 4
Views: 39305
Reputation: 385
the datagridview will count the last empty row so make sure to
look for AllowUserToAddRows property of datagridview and set it to False.
Or add this to your code, in my case i used a label and i named it labelTotalResult, do this if you want to keep the property as true
labelTotalResult.Text = (dataGridView1.RowCount - 1).ToString();
Upvotes: 0
Reputation: 8214
If I've understood your question correctly you want the TextBox value to change automatically when rows are added or removed because at the moment you have to press a button to refresh. Am I right?
If so just subscribe to the .RowsAdded and .RowsRemoved events and update the TextBox from there.
dataGridView1.RowsAdded += RowsAdded;
dataGridView1.RowsRemoved += RowsRemoved;
private void RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
txtTotalItem.Text = dataGridView1.Rows.Count.ToString();
}
private void RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
txtTotalItem.Text = dataGridView1.Rows.Count.ToString();
}
Upvotes: 4
Reputation: 994
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();
Upvotes: 12