How to exit a cycle in C #?

4

I need to exit foreach when the value is equal to 1

foreach (DataGridViewRow dr in dgvValetes)
    if(dr.Cells["valor"].toString()=="1")
        //Sair aqui

I do not know how to do ...

    
asked by anonymous 16.06.2016 / 12:36

2 answers

6

To exit the loop use the command break

foreach (DataGridViewRow dr in dgvValetes)
   if (dr.Cells["valor"].ToString()=="1")
      break;
    
16.06.2016 / 12:46
7

Assuming the condition is correct and does what you want, you only need break to exit of the loop there:

foreach (var dr in dgvValetes) {
    if (dr.Cells["valor"].ToString() == "1") {
        break;
    }
}

Note that I preferred to put the keys to avoid future maintenance problems and create some confusion.

For historical reasons (there was an error in the other answer):

Have string changed by using the == operator with the CompareTo() method does not make any sense.

    
16.06.2016 / 13:16