FutureDev
FutureDev

Reputation: 155

How to check if datagridview returns 0 row with specific value

I need something like search datagridview if a row cell has this value(D) and if no row has cell value like this if would do something. this is my code but its wrong

ID  Qty  Price   D
==================
1    5    2.00   D
2    4    3.00
3    2    10.00  D

thats the example datagridview my code is.

 private void noD()
    {
        foreach (DataGridViewRow row in dgvPOScart.Rows)
        {
            if (Convert.ToChar(row.Cells[3].Value) != 'D')
            {
                // If no rows withcell[3] having a value of D
                  // (For example only item is with ID 2)
                //Do this

            }

        }

    }

Upvotes: 0

Views: 1061

Answers (2)

FutureDev
FutureDev

Reputation: 155

Manage to solve it using this code. as per tip of sir LarsTech and sir CMedina.

 private bool withD()
    {
        foreach (DataGridViewRow row in dgvPOScart.Rows)
        {
            if (row.Cells[3].Value.ToString().Equals("D"))
            {
                return true;
            }

        }
        return false;

    }

and calling it by

 if(withD())
        {
            //code if a row with a cell value of "D" is found
        }
        else
        {
            //code if no cell with a value of "D" is found
        }

Upvotes: 0

CMedina
CMedina

Reputation: 4222

Try this code, It's working for me!

int allDValuecount = 0;
int allOtherValueCount = 0;
int rowsCount = DataGridViewRow.Rows.Cont;
foreach(DataGridViewRow row in DataGridViewRow.Rows)
{
    if(!row.Cells[3].Value.ToString().Equals("D"))
    {
        allOtherValueCount++;
    }else
    {
        allDValuecount++;
    }
}

if(allDValuecount == rowsCount){//code for all D values}
if(allOtherValueCount == rowsCount){//code for other values}

Upvotes: 1

Related Questions