How to go through a datagridview and add when a code matches? C #

0

I need to go through a column of my DataGridView called "code" when I insert one in the textbox, if I find it simply that the column called "Captured" of the same row increases by 1, otherwise it does not do anything, it's like a supermarket box, I'm checking an order with a barcode reader

If someone could help me with some idea of how to do it (I do not need all the code) I would appreciate it very much, I am very new with this, thanks in advance

Edit 12/18/2018

Thank you very much, modify a code that you told me below, in the end it worked like this:

foreach (DataGridViewRow fila in dataGridView1.Rows)
        {
            String a = null;
            a = Convert.ToString(fila.Cells[0].Value);
            if (a == txtCodigo.Text)
            {
                int n = Convert.ToInt32(fila.Cells[3].Value);
                n = n + 1;
                fila.Cells[3].Value = n;
            }
        }
    
asked by Demar Severiano 18.12.2018 в 02:30
source

2 answers

1

You could try this:

foreach(GridViewRow fila in TuDataGridView.Rows){
  if(fila.Cells[0].Value.ToString() == TextBox.Text)
  {
    fila.Cells[3].Value = 1;
  }
}

I would not be aware that if the data types of the expression of the IF are fine, but with this you could guide a little and we are delaying the answer until we find the solution. Anyway if you think to handle all the data as string, the best way to buy them would be the following

if(fila.Cells[0].Value.ToString().Equals(TextBox.Text) == 0)
    
answered by 18.12.2018 / 03:48
source
1

To locate a row in the grid you do not need to go through it, you can use linq, with a simple query to access the row

var row = (from item in DataGridView1.Rows.Cast<DataGridViewRow>()
             where item.Cells["Codigo"].Value.ToString() == txtCodigo.Text
           select item).FirstOrDefault();

if(row != null){
   var cellCapturado = row.Cells["Capturado"];
   cellCapturado.Value = Convert.ToInt32(cellCapturado.Value) + 1;
}

imagine I wanted to add if more than one reading of the same code was done

Also the query linq could have been done in the following way

var row = DataGridView1.Rows.Cast<DataGridViewRow>()
                       .FirstOrDefault(item=> item.Cells["Codigo"].Value == txtCodigo.Text);

is another way using extension methods

    
answered by 18.12.2018 в 11:48