Comparando cadenas en C# con OR en una declaración if

I'm a newbie to C#, but can't seem to find anything about this problem. Here's what I'm trying to do:

string testString = txtBox1.Text;
string testString2 = txtBox2.Text;

if ((testString == "") || (testString2 == ""))
{
    MessageBox.Show("You must enter a value into both boxes");
    return;
} 

Basically I need to check to see if either txtBox1 or txtBox2 is blank. However I'm getting an error when running this. What's the proper way to do this (or is my approach all wrong)?

preguntado el 01 de julio de 12 a las 17:07

What does "accept" mean? -

sorry I have clarified the problem, my original question did not fully include everything. I pressed save too soon before I realized it did not cover the actual problem I was having. -

Cual es el error? -

In the code sample you provided, there is a closed parentheses ')' missing in the if. -

@Tibi: the code looks fine to me. -

6 Respuestas

Since you want to check whether textboxes contains any value or not your code should do the job. You should be more specific about the error you are having. You can also do:

if(textBox1.Text == string.Empty || textBox2.Text == string.Empty)
   {
    MessageBox.Show("You must enter a value into both boxes");
   }

EDIT 2: based on @JonSkeet comments:

Usage of string.Compare is not required as per OP's original unedited post. Cadena.Equals should do the job if one wants to compare strings, and StringComparison may be used to ignore case for the comparison. string.Compare should be used for order comparison. Originally the question contain this comparison,

string testString = "This is a test";
string testString2 = "This is not a test";

if (testString == testString2)
{
    //do some stuff;
}

the if statement can be replaced with

if(testString.Equals(testString2))

or following to ignore case.

if(testString.Equals(testString2,StringComparison.InvariantCultureIgnoreCase)) 

respondido 11 mar '15, 16:03

I would personally suggest using Equals por igualdad comparisons. That's what it's there for, after all. - jon skeet

@JonSkeet, I agree, I wasn't sure about the original unedited post, if the OP want to compare for equality or wants to compare the strings ignoring case, - Habib

Why on earth would case matter when the OP is comparing for the strings being vacío? Even if you do want to do a case-insensitive comparison, you can still use Equals con un StringComparison, which is clearer than using Compare OMI. Compare should be used for an solicite comparison, not equality. I'm amazed this answer has been accepted, as I can't see how it helps the OP with the question as stated. - jon skeet

@JonSkeet, that was my miss understanding that the OP want's to compare strings, not the empty strings. Earlier there were two string variables with values and OP was comparing them using ==, later the edited post specified comparing against empty string. Even I am surprised at the answer being accepted. Probably due to edited part of comparing textBox1.Text == string.Empty, but again there are other answers using Equals which are much better - Habib

Can you mention the reason for using string.Empty más bien que "", if there's any? I'm no good C# programmer (only Java/Scala expert) and the point of string.Empty existing at all is not clear to me. - Blaisorblade

Here's a more valid way which also check if your textbox is filled with only blanks.

// When spaces are not allowed
if (string.IsNullOrWhiteSpace(txtBox1.Text) || string.IsNullOrWhiteSpace(txtBox2.Text))
  //...give error...

// When spaces are allowed
if (string.IsNullOrEmpty(txtBox1.Text) || string.IsNullOrEmpty(txtBox2.Text))
  //...give error...

The edited answer of @Habib.OSU is also fine, this is just another approach.

Respondido 06 Jul 12, 23:07

in your comments you had the 'not' in the wrong place, if the method names make any sense. I assumed it was a typo and edited the answer, please correct it if the current one is actually wrong (but then please explain the weirdness). - Blaisorblade

@Blaisorblade No. In OP's code, he's throwing error message when string is equal to empty or contains white-space, so if string is empty, then throw the error or if string is white-space throw the error. - Code0987

I see, sorry. I thought you implemented the intro. I've added comments to clarify the answer. - Blaisorblade

tratan

if (testString.Equals(testString2)){
}

Respondido 01 Jul 12, 17:07

This is correct, no clue why someone would downvote this other than being a duplicate but posted at the exact same time. Never mind the asholes buddy - eric herlitz

The question is not about comparing the two strings with each other; the code should check if either is empty. The original question was different though and this fue a sensible answer, so downvotes are probably not appropriate. - Blaisorblade

The code provided is correct, I don't see any reason why it wouldn't work. You could also try if (string1.Equals(string2)) como se sugiere.

Que hacer if (something OR something else), Utilizar ||:

if (condition_1 || condition_2) { ... }

Respondido 01 Jul 12, 17:07

utilizan el if (testString.Equals(testString2)).

Respondido 01 Jul 12, 17:07

The question is not about comparing the two strings with each other; the code should check if either is empty. The original question was different though and this fue a sensible answer, so downvotes are probably not appropriate. - Blaisorblade

Tratar:

    if (textBox1.Text == "" || textBox2.Text == "")
    {
        // do something..
    }

En lugar de:

    if (textBox1.Text == string.Empty || textBox2.Text == string.Empty)
    {
        // do something..
    }

Because string.Empty is different than - "".

Respondido el 24 de Septiembre de 17 a las 18:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.