Home > Back-end >  Loop based on null value of DataGridView cell
Loop based on null value of DataGridView cell

Time:12-11

I'm still new to using c#. I searched many threads in the forum but couldn't find a solution. I would be grateful if you help.

The problem I can't solve; If dataGridView2.Rows[i].Cells[5] value=null or empty then run the code below.

If it's full, I want it to increment [i] and move to the next line.

Loop stop point = column length of DataGridView

for (int i = 0; i < **???**; i  )
{
    if (**???**)
    {

        TxtSayKod.Text = dataGridView2.Rows[i].Cells[2].Value.ToString()   dataGridView2.Rows[i].Cells[10].Value.ToString();
        TxtHome.Text = dataGridView2.Rows[i].Cells[3].Value.ToString();
        TxtAway.Text = dataGridView2.Rows[i].Cells[10].Value.ToString();
        button1.PerformClick();
        Thread.Sleep(3000);
        btnupdate.PerformClick();                    
    }
    ...
}

CodePudding user response:

Do like this, run a loop for all rows and check the respective cell.

foreach (DataGridViewRow row in dataGridView2.Rows)
{
    if (row.Cells[5].Value is not null && row.Cells[5].Value.ToString() == string.Empty)
    {

    }
}

CodePudding user response:

You can simplify looping by using a foreach-loop

foreach (DataGridViewRow row in dataGridView2.Rows)
{
    if (row.Cells[5].Value is null) // Remove this: ;
    {
        string away = row.Cells[10].Value.ToString();
        TxtSayKod.Text = row.Cells[2].Value.ToString()   away;
        TxtHome.Text = row.Cells[3].Value.ToString();
        TxtAway.Text = away;
        button1.PerformClick();
        Thread.Sleep(3000);
        btnupdate.PerformClick();                    
    }
}

Even when using a for-statement, you could assign the current row to a variable to simplify the following code:

for (int i = 0; i < dataGridView2.Rows.Count; i  )
{
    var row = dataGridView2.Rows[i]; 
    if (row.Cells[5].Value is null)
    {
        string away = row.Cells[10].Value.ToString();
        ...
    }
}

Note that test is int only works if the value has been assigned to the cell as int and not say as number.ToString(). Otherwise, if it was as string, test:

if (row.Cells[3].Value is null or string { Length: 0 })

This uses a type pattern followed by a property pattern. See: Pattern Matching in C# 8.0

The semicolon (;) after your if (**???**) ; (in the unedited question) terminates the if-statement. Remove it to have to following code block to be executed as part of the if.

  • Related