Reputation: 21108
I want to add one more function/property to a text property of a textbox like this.
txtControl.Text.IsEmpty();
or txtControl.Text.IsEmpty;
which returns me bool value.
I dont want to compare for empty string every time.
i.e.
if(txtControl.text==string.Empty)
{}
else
{}
Can we do some other way also
if just want to do it like
if(txtControl.text.isEmpty){}
Upvotes: 1
Views: 6179
Reputation: 17281
The text property is a string. The string class contains a static method IsNullOrEmpty()
So you could use if (String.IsNullOrEmpty(txtControl.Text)) {} else {}
Option2 is to create a extra property on the textbox:
public class MyTextbox : Textbox
{
public bool IsEmpty
{
get
{
return String.IsNullOrEmpty(this.Text);
}
}
}
You can use it like this: if (txtMyTextbox.IsEmpty) {} else {}
Upvotes: 2
Reputation: 43217
In c# 3.0 you can do something like this..
namespace ExtensionMethods
{
public static class MyExtensions
{
public static bool IsTextEmpty(this Textbox txtBox)
{
return string.IsNullOrEmpty(txtBox.Text);
}
}
}
Then you can use it like this.
bool isEmpty = yourTxtBox.IsTextEmpty();
This will work for all textbox instances across your application, provided you have referred the namespace of extension method. If you have your custom textbox then replace the type TextBox with the type of your custom Textbox. It may look like this if you have your own TextBox..
namespace ExtensionMethods
{
public static class MyExtensions
{
public static bool IsTextEmpty(this MyTextbox txtBox)
{
return string.IsNullOrEmpty(txtBox.Text);
}
}
}
Upvotes: 8
Reputation: 499382
The Text
property is a string, which already has a IsNullOrEmpty
function on it.
Upvotes: 0
Reputation: 72930
Why not create an extension method:
public static bool HasEmptyText(this TextBox textBox)
{
return string.IsNullOrEmpty(textBox.text);
}
Then you can just use txtControl.HasEmptyText()
.
Upvotes: 2