Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if(dataGridView1.Rows[i].Cells["Company"].Value == "EBC")
                {
                    int rowcount = dataGridView1.Rows[i].Cells.Count;
                    label6.Text = Convert.ToString(rowcount);
                }
            }


What I have tried:

I want to count the row which has the value "EBC"and print it on the label. so Please help...
Posted
Updated 28-Jan-17 6:57am
v2

The code you posted does not count rows, its counting the number of cells in that row that has the EBC value. Is that what you want or is the below accurate?

If your trying to show the rowcount while looping you just increase the rowcount by 1 inside the if statement, and then set the label text to that number as a string. Note the use of .ToString() instead of Convert, though they produce the same result.
C#
int rowCount = 0;

for (int i = 0; i < dataGridView1.Rows.Count; i++){
    if(dataGridView1.Rows[i].Cells["Company"].Value == "EBC"){
        rowCount++;
        label6.Text = rowCount.ToString();
    }
}


Otherwise you can do the full looping and checks, incrementing the rowCount and then just set the label once at the end.
C#
int rowCount = 0;

for (int i = 0; i < dataGridView1.Rows.Count; i++){
    if(dataGridView1.Rows[i].Cells["Company"].Value == "EBC"){
        rowCount++;
    }
}

label6.Text = rowCount.ToString();
 
Share this answer
 
v3
Comments
Member 12857358 28-Jan-17 13:27pm    
it shows the value 0 but i have 5 rows which contains the value "EBC"
An alternative approach (not necessarily better) is to convert the column of the datagridview to a List e.g.

C#
const int colWithEbc = 1;

var list = new List<string>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
       if (row.Cells[colWithEbc].Value != null)
             list.Add(row.Cells[colWithEbc].Value.ToString());
}
or
C#
List<string> list = dataGridView1.Rows
            .OfType<DataGridViewRow>()
            .Where(x => x.Cells[1].Value != null)
            .Select(x => x.Cells[1].Value.ToString())
            .ToList();

And then just count the items in the list that fit the criteria e.g.
C#
label6.Text  = list.Count(n => n.ToString().Equals("EBC")).ToString();
 
Share this answer
 
Comments
Member 12857358 28-Jan-17 13:35pm    
Thanks its working

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