blah blah blah is here! blah blah » Close

up1down
link

Guys this may be a simple answer, but i can't get it to work how i want.
Example: the following code counts the rows in my datagrid and it counts them fine:

label6.Text = (usedDataGridView.Rows.Count - 1).ToString();


Now how could i use the above code to count only the rows that contain a value off "CLOSED" in column [2]?

last answered one year ago

3 answers

up2down
link

To do that, you need to iterate through each row to see whether column 2 contains the value in question and count those that do. Here's the code:

int count = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) break;
object obj = row.Cells[2].Value;
if (obj != null && !DBNull.Value.Equals(obj) && obj.ToString() == "CLOSED") count++;
}

up0down
link

vuples that works great, tell me though i've put the following in the 'if 'statement - it works but is that the correct way?

int count = 0; foreach (DataGridViewRow row in usedDataGridView.Rows)
{
if (row.IsNewRow) break;
object obj = row.Cells[2].Value;
if (obj != null && !DBNull.Value.Equals(obj) && obj.ToString() == "CLOSED") count++;
{
label6.Text = count.ToString();
}
}


The above displays the counted value on the label, just what i wanted. would really like to know if i'm using it correct though?

up1down
link

Updating the Text property of your label in every iteration isn't necessary. Do this in stead:

int count = 0; foreach (DataGridViewRow row in usedDataGridView.Rows)
{
if (row.IsNewRow) break;
object obj = row.Cells[2].Value;
if (obj != null && !DBNull.Value.Equals(obj) && obj.ToString() == "CLOSED") count++;
}
label6.Text = count.ToString();

Thanks foamy, and vulpes of course.

Feedback