It is possible to write the following condition?
if (textbox.text != null)
Because when I have written this condition in my program, it throws an exception.
If the data type of textbox
is string
then it is also nullable ?
It is possible to write the following condition?
if (textbox.text != null)
Because when I have written this condition in my program, it throws an exception.
If the data type of textbox
is string
then it is also nullable ?
The only reason that particular line of code should cause an error is if the textbox
variable itself was actually null. What is the exact exception?
Also a handy tip: if you want to check for an empty text box I recommend String.IsNullOrWhitespace(textbox.text)
which will return a bool. It's great for if statements like this.
Based on the OP's commentary in the main post, and his other comment stating that the exception said "Input string was not in correct format", it looks like it's not the line of code above that threw the exception (although it should correctly be .Text
instead of .text
).
Rather, this FormatException
indicates that it probably is the Convert.ToDouble(textbox.Text)
that is unable to convert the content of textbox
to a double
. Are you sure you entered a correct double
value? This issue could also be related to your culture settings.
"if (textbox.Text != null)"
Because when I have written this condition in my program, it throws an exception.
If data type of textbox is string then it is also nullable ?
Yes. textbox is just a variable that holds a reference to a class instance so its default value is null; You should be careful accessing .Text property because if textbox value is set to null you will have NullReferenceException.
So i'd do something like this (assuming it's method or event handler) :
void MyMethod()
{
if(textbox == null) return;
if(String.IsNullOrWhiteSpace(textbox.Text)) return;
// your code here if textbox.Text has valid value
}
P.S. if you're converting this string to Double it's different story:
double GetDouble()
{
if(textbox == null) throw new NullReferenceException("textbox is null");
if(String.IsNullOrWhiteSpace(textbox.Text)) throw new ArgumentException("textbox.Text contains null or white spaces");
double result = 0;
if(!Double.TryParse(textbox.Text, out result)) throw new ArgumentException("textbox.Text has invalid number");
return result;
}