How to increase the value of a cell in a DataGridView when a code matches? C #

1

I'm doing a kind of verifier, I need to press a button to check if the code of my TextBox matches in some data of the column "Code" and if so, increase by 1 the value of "Captured", this is what I'm trying now:

 foreach (DataGridViewRow fila in dataGridView1.Rows)
        {
            if (fila.Cells[0].Value.ToString() == txtCodigo.Text)
            {
                int n = Convert.ToInt32(fila.Cells[3].Value);
                n = n + 1;
                fila.Cells[3].Value = n;
            }
        }

And this is the image of my table

The problem I have is that this error marks me in the execution of the program

If you could help me locate my mistake, I would be very grateful, I'm new to this, thanks in advance

    
asked by Demar Severiano 19.12.2018 в 01:53
source

1 answer

1

I've tried it and the function is trying to access the bottom row of the grid, which is supposed to create a new row.

As in cell 0, there is no value, when you try to apply the ToString to the value, it gives the error. You could solve it with the code that I indicated, which ignores the row when the value of the cell is null.

I hope it serves you.

private void button1_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow fila in dataGridView1.Rows)
        {
            if (fila.Cells[0].Value != null){
                if (fila.Cells[0].Value.ToString() == txtCodigo.Text)
                {
                    int n = Convert.ToInt32(fila.Cells[3].Value);
                    n = n + 1;
                    fila.Cells[3].Value = n;
                }
            }

        }
    }
    
answered by 19.12.2018 / 08:43
source