Reputation: 425
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
}
}
Upvotes: 2
Views: 92598
Reputation: 65342
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 to update it just 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();
Upvotes: 9
Reputation: 14874
Move the declation of x
to outer scope.
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
}
The improved one:
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
Upvotes: 5
Reputation: 30875
You have several problems in that code.
The reason you can not increment x varaible. Is that you declare it inside the loop. Because of that it is "recreated" for each run of loop.
Next issue might be that you are using the preincrementation instead of post increment,the last thing is that generally is better to compare constant to variable. This protect you against unwanted NullPointerException.
So the improved code should look like:
int x = 0; //Declaration of x
for(int i=0; i< Product.Items.Count; i++) { //Post increment
if("3".Equals(table.Rows[i]["id"]) { // Check constant against variable.
x++; // Post increment x = x + 1;
}
}
lblCounte.Text = Convert.ToString(x); //Assign the int result to String member.
In case of any other questions do not hesitate to write them down.
Peace.
Upvotes: 3
Reputation: 38005
lblCounter.Text = table.Rows.OfType<DataRow>().Count(row => row["id"] == 3).ToString();
Edited based on KooKiz's comment and assuming table is a DataTable
.
Upvotes: 15
Reputation: 11363
int x = 0;
for (int i = 0; i < Product.Items.Count; ++i)
{
if (table.Rows[i]["id"].ToString() == "3")
{
x++;
}
}
lblCounter.Text = x.ToString();
Upvotes: 5
Reputation: 6873
If I understand well your question.
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()
}
Upvotes: 0
Reputation: 25200
You need to initialize x
outside the loop, then call .ToString()
to find the string value. (That's a method, not a property, so it needs the final ()
.
Try this:
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();
}
}
You can also use x++
to increment in one step but personally I prefer to make it explicit.
Upvotes: 1