检查文本框是否为空

Check Whether a TextBox is empty or not

我有一个文本框。我想检查它是否为空。

哪种方式更好

if(TextBox.Text.Length == 0)

if(TextBox.Text == '')

?

您应该使用 String.IsNullOrEmpty() 来确保它既不为空也不为空(不知何故):

if (String.IsNullOrEmpty(textBox1.Text))
{
    // Do something...
}

更多示例here

出于实际目的,您还可以考虑使用 String.IsNullOrWhitespace(),因为期望空格作为输入的 TextBox 可能会否定任何目的,除非让用户为内容选择自定义分隔符。

我觉得

string.IsNullOrEmpty(TextBox.Text)

string.IsNullOrWhiteSpace(TextBox.Text)

是您最好的选择。

Farhan 的答案是最好的,我想补充一点,如果您需要满足这两个条件,添加 OR 运算符就可以,如下所示:

if (string.IsNullOrEmpty(text.Text) || string.IsNullOrWhiteSpace(text.Text))
{
  //Code
}

请注意,使用 stringString

是有区别的

如果在XAML中,可以使用Text属性中的IsEmpty检查TextBox中是否有文本。

结果它冒泡到 CollectionView.IsEmpty(不在字符串 属性 上)以提供答案。此文本框水印示例,其中显示两个文本框(在编辑中,一个带有水印文本)。第二个文本框(水印之一)上的样式将绑定到主文本框上的 Text 并相应地打开 on/off。

<TextBox.Style>
    <Style TargetType="TextBox">
        <Style.Triggers>
            <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                    <Condition Binding="{Binding ElementName=tEnterTextTextBox, Path=IsKeyboardFocusWithin}" Value="False" />
                    <Condition Binding="{Binding ElementName=tEnterTextTextBox, Path=Text.IsEmpty}" Value="True" />
                </MultiDataTrigger.Conditions>
                <Setter Property="Visibility" Value="Visible" />
            </MultiDataTrigger>
            <DataTrigger Binding="{Binding ElementName=tEnterTextTextBox, Path=IsKeyboardFocusWithin}" Value="True">
                <Setter Property="Visibility" Value="Hidden" />
            </DataTrigger>
            <DataTrigger Binding="{Binding ElementName=tEnterTextTextBox, Path=Text.IsEmpty}" Value="False">
                <Setter Property="Visibility" Value="Hidden" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBox.Style>

  • CollectionView.IsEmpty explanation
  • Help Text WaterMark to Disappear when user Types in (answer)(这是我从上面给出的部分答案中使用的完整示例)。

另一种方式:

    if(textBox1.TextLength == 0)
    {
       MessageBox.Show("The texbox is empty!");
    }

您可以将该代码放入 ButtonClick 事件或任何事件中:

//Array for all or some of the TextBox on the Form
TextBox[] textBox = { txtFName, txtLName, txtBalance };

//foreach loop for check TextBox is empty
foreach (TextBox txt in textBox)
{
    if (string.IsNullOrWhiteSpace(txt.Text))
    {
        MessageBox.Show("The TextBox is empty!");
        break;
    }
}
return;

我认为检查文本框是否为空+是否只有字母的最简单方法:

public bool isEmpty()
    {
        bool checkString = txtBox.Text.Any(char.IsDigit);

        if (txtBox.Text == string.Empty)
        {
            return false;
        }
        if (checkString == false)
        {
            return false;
        }
        return true;
    }