How to get out of a cycle in C#?

Asked

Viewed 2,547 times

6

I need to get out of the foreach when the value is equal to 1

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

I don’t know how to do...

  • Post your complete code

  • I’ve already put the cycle code

2 answers

8


To exit the cycle use the command break

foreach (DataGridViewRow dr in dgvValetes)
   if (dr.Cells["valor"].ToString()=="1")
      break;
  • 1

    "[...]It should not be used when the Primary purpose of the method call is to determine whether two strings are equivalent." Excerpt taken from MSDN on string.Compareto(). MSDN https://msdn.microsoft.com/pt-br/library/35f0x18w(v=vs.110). aspx

  • 1

    Edited, thank you

8

Assuming the condition is correct and you do what you want, you just need the break to get out of the loop there:

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

I put in the Github for future reference.

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 the comparison of string using the operator == by the method CompareTo() doesn’t make any sense.

  • Edited, thank you

  • Exactly what I was going to say. Change == for CompareTo() doesn’t make any sense.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.