user1007103 user1007103 - 2 months ago 10
C# Question

Increment by 1 in c#

I'm trying to count the rows in a DataList where id is 3 and put the value in a label.

for (int i = 0; i < Product.Items.Count; ++i)
{
if (table.Rows[i]["id"].ToString() == "3")
{
int x = x + 1;
lblCounter.text = x.ToString
}
}

Answer
int x = x + 1;

Will not work. You have to do something like

int x = 0;

before the loop and

x = x + 1;

inside it. Additionally, you might want to put lblCounter.text = x.ToString after the loop, so as tu just update it once.

This makes

int x = 0;
for (int i = 0; i < Product.Items.Count; ++i)
     if (table.Rows[i]["id"].ToString() == "3")
          x = x + 1;
lblCounter.text = x.ToString();