Ayman Ayman - 3 months ago 19
ASP.NET (C#) Question

Check if gridview column on each row has the same values

How can i check if grid-view column on each row has the same values.

what is the condition that will be applied on below code.

Code

int y = 0;
foreach (GridViewRow row in gridreq.Rows)
{
string catid = row.Cells[2].Text;
if (//condition)
{
y = y + 1;

}
}

if (y == 0)
{

//code

}
else
{
//code
}

Answer

Other than a foreach inside your foreach, there is no feasible way to check a row's value against all other row's values. Some workarounds:

Maybe you could check against the first value?

int y = 0;
var checkItem = gridreq.Rows[0].Cells[2].Text;
foreach (GridViewRow row in gridreq.Rows)
{
    string catid = row.Cells[2].Text;
    if (catid == checkItem)    //or use String.compare here
    {
        y = y + 1;

    }
}

Another way is to check the value against that of the row before it.

int y = 0;
string catidCheck = "";
foreach (GridViewRow row in gridreq.Rows)
{
    string catid = row.Cells[2].Text;
    if (catid == catidCheck)    //or use String.compare here
    {
        y = y + 1;
    }
    catidCheck = catid;
}