Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
int count = 0;

private void timer1_Tick(object sender, EventArgs e)
{
count = metroGrid1.SelectedRows.Count;
txtSumClient.Text = count.ToString();
txtSumClient.ForeColor = Color.Red;
}

What I have tried:

Code above is my current code, The issue is I have to select the datagridview data before it count to the textbox, what I need is when the form load the count (Number of Clients) is the textbox. Please guys help me. Thank you in advance.
Posted
Updated 17-Apr-17 5:47am
Comments
Michael_Davies 16-Apr-17 7:41am    
The DataBindingComplete event might work for any data binding change along with the form show or load event.
Maciej Los 16-Apr-17 12:40pm    
RowCount or Rows.Count isn't enough?

1 solution

This will do it:
C#
private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    txtSumClient.Text = DataGridView1.Rows.Count.ToString();
    txtSumClient.ForeColor = Color.Red
}
Specifically you should not use a Timer.
I'm a little concerned about your comment
Quote:
The issue is I have to select the datagridview data before it count to the textbox what I need is when the form load the count (Number of Clients) is the textbox
You cannot select any data in the datagridview until the form is loaded. So note that the code I've given you so far will count all of the rows in the datagrid. It will always be one row out unless you have disabled the user's ability to add new rows e.g. (I have a function ReadData that returns a DataTable)
C#
private void Form1_Load(object sender, EventArgs e)
{
    DataGridView1.AllowUserToAddRows = false;
    DataGridView1.DataSource = ReadData();
}
If you want a textbox to show the number of selected rows then the event you need to hook up is the SelectionChanged event e.g.
C#
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
    txtSelected.Text = DataGridView1.SelectedRows.Count.ToString();
}
Assuming you have DataGridView1.MultiSelect = true; (either in code or in the Properties window)
 
Share this answer
 
Comments
Member 13111663 17-Apr-17 17:51pm    
Thanks guys!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900