Reputation: 3578
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.
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..
Upvotes: 1
Views: 1365
Reputation: 107247
string.IsNullorEmpty()
is a static method, invoked as follows:
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.
Upvotes: 5
Reputation: 62093
Can it be this is not realted to he string test?
ErrorProvider errorProvider = new ErrorProvider();
Hmpf. Seriously. The ErrorProvider should exist on the form. 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.
The ErrorProvider should be put onto the form.
Upvotes: 0
Reputation: 1500525
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.
You could write an extension method which could cope with null, but there isn't one in the framework as far as I know.
Upvotes: 7
Reputation: 55489
Change your IF condition to -
if( string.IsNullOrEmpty(txtHost.Text) )
{
...
}
Upvotes: 0