3

我是 C# 的新手,但似乎找不到关于这个问题的任何信息。这是我正在尝试做的事情:

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

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

基本上我需要检查 txtBox1 或 txtBox2 是否为空白。但是,运行此程序时出现错误。这样做的正确方法是什么(或者我的方法全错了)?

4

6 回答 6

7

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. String.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)) 
于 2012-07-01T16:38:33.117 回答
3

这是一种更有效的方法,它还可以检查您的文本框是否仅填充空白。

// 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...

@Habib.OSU 的编辑答案也很好,这只是另一种方法。

于 2012-07-01T17:02:31.073 回答
1

try

if (testString.Equals(testString2)){
}
于 2012-07-01T16:35:56.513 回答
1

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

To do if (something OR something else), use ||:

if (condition_1 || condition_2) { ... }
于 2012-07-01T16:37:14.973 回答
0

use if (testString.Equals(testString2)).

于 2012-07-01T16:35:25.733 回答
0

尝试:

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

代替:

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

因为 string.Empty 不同于 -""。

于 2017-09-24T17:42:14.837 回答