我是C#的新手,但似乎找不到关于此问题的任何信息。这是我想做的事情:
string testString = txtBox1.Text;
string testString2 = txtBox2.Text;
if ((testString == "") || (testString2 == ""))
{
MessageBox.Show("You must enter a value into both boxes");
return;
}
Run Code Online (Sandbox Code Playgroud)
基本上,我需要检查txtBox1或txtBox2是否为空白。但是,运行此程序时出现错误。这样做的正确方法是什么(或者我的方法是否全部错误)?
由于您要检查文本框是否包含任何值,因此您的代码应该完成这项工作。您应该更详细地说明所遇到的错误。您也可以:
if(textBox1.Text == string.Empty || textBox2.Text == string.Empty)
{
MessageBox.Show("You must enter a value into both boxes");
}
Run Code Online (Sandbox Code Playgroud)
编辑2:基于@JonSkeet评论:
根据OP的原始未编辑帖子,不需要使用string.Compare。如果要比较字符串,String.Equals应该起作用,并且StringComparison可以用来忽略大小写进行比较。string.Compare应该用于订单比较。本来的问题包含此比较,
string testString = "This is a test";
string testString2 = "This is not a test";
if (testString == testString2)
{
//do some stuff;
}
Run Code Online (Sandbox Code Playgroud)
if语句可以替换为
if(testString.Equals(testString2))
Run Code Online (Sandbox Code Playgroud)
或跟随以忽略大小写。
if(testString.Equals(testString2,StringComparison.InvariantCultureIgnoreCase))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87472 次 |
| 最近记录: |