简体   繁体   English

string.empty和string.isnullorempty

[英]string.empty and string.isnullorempty

I have a function like this which checks whether the field is empty or what and if empty then get the setError icon aside the textbox. 我有一个类似这样的函数,它检查该字段是否为空或什么,如果为空,则将setError图标放在文本框旁边。

      private bool ValidateHost()
      {
        ErrorProvider errorProvider = new ErrorProvider();
        bool isValid = true;

        //If the txtHost is empty, show a message to user            
        if(txtHost.Text == string.Empty)
            {
            errorProvider.SetError(txtHost, "Please enter the host address");
            isValid = false;
            }
        else
            errorProvider.SetError(txtHost, string.Empty);
        return isValid;
      }

but when I tried to use string,isnullorempty then I am not getting the seterror icon.. Can you guys plz tell me what is the proper way of using string.isnullorempty in this case.. 但是当我尝试使用string,isnullorempty时,我没有得到seterror图标。你们能告诉我在这种情况下使用string.isnullorempty的正确方法是什么。

My guess is you tried to use it as if it were an instance method, like this: 我的猜测是您试图像使用实例方法一样使用它,如下所示:

if (txtHost.Text.IsNullOrEmpty())

It's not an instance method - it's a static method, so you use it like this: 它不是实例方法,而是静态方法,因此您可以这样使用它:

if (string.IsNullOrEmpty(txtHost.Text))

It's not an instance method because otherwise if txtHost.Text was null, the method call would throw a NullReferenceException , which is precisely what we're trying to avoid. 它不是实例方法,因为如果txtHost.Text为null,则该方法调用将抛出NullReferenceException ,而这正是我们要避免的情况。

You could write an extension method which could cope with null, but there isn't one in the framework as far as I know. 可以编写一种扩展方法来应对null,但据我所知,框架中没有一个扩展方法。

string.IsNullorEmpty() is a static method, invoked as follows: string.IsNullorEmpty()是一个静态方法,其调用方式如下:

if (string.IsNullOrEmpty(txtHost.Text))
{
    errorProvider.SetError(txtHost, "Please enter the host address"); 
    isValid = false;
}

You can also consider the similar string.IsNullOrWhitespace if spaces, tabs, etc are also invalid. 如果空格,制表符等也无效,则也可以考虑使用类似的string.IsNullOrWhitespace

Change your IF condition to - 将您的IF条件更改为-

if( string.IsNullOrEmpty(txtHost.Text) ) 
{
  ...
}

Can it be this is not realted to he string test? 难道这不是他字符串测试所必需的吗?

ErrorProvider errorProvider = new ErrorProvider(); ErrorProvider errorProvider =新的ErrorProvider();

Hmpf. Seriously. 说真的 The ErrorProvider should exist on the form. ErrorProvider应该存在于表单上。 You are just creating one on teh fly (which turns invalid at the end of hthe method) and are not even hooking those up properly in the form. 您只是在动态创建一个(在hthe方法结束时变为无效),甚至没有将它们正确地挂接到表单中。

The ErrorProvider should be put onto the form. ErrorProvider应该放在表单上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM