Reputation: 25
How can I convert a textbox into a float only when the textbox has value?
I currently have this float test = (float)Convert.ToDouble(textbox.Text);
It works fine, But gives an error if the textbox is empty.
Upvotes: 0
Views: 740
Reputation: 11389
A very common way is to use double.TryParse
to do the conversion. This way you can handle empty and invalid values with a single statement.
bool success = double.TryParse(textbox.Text, out value);
Don't forget to check success
and handle a possible failure.
Upvotes: 0
Reputation: 2272
I think that better solution will be:
float test = float.NaN;
if(float.TryParse(textbox.Text, out test ))
{
// your code here
}
Upvotes: 1
Reputation: 169
It really is as simple as including this in an If statement.
float test;
if(textbox.Text.Length > 0) //Or (textbox.Text != "")
test = (float)Convert.ToDouble(textbox.Text);
As an additional suggestion, multiple layers of validation is always a good thing. If you have something like a submit button, you should test against required fields being empty on the UI BEFORE it gets to the point where it is converted.
Upvotes: 0
Reputation: 3965
There are many ways to do this, but generally you test with an if
. For example:
float test;
if (!string.IsNullOrWhiteSpace(textbox.text))
test = (float)Convert.ToDouble(textbox.Text);
Upvotes: 0