Is there a way to avoid throwing/catching exceptions when validating Textboxes used for number entry?
In the pursuit of elegant coding, I'd like to avoid having to catch an exception that I know well may be thrown when I try to validate that the Text field of a Textbox is an integer. I'm looking for something similar to the TryGetValue for Dictionary, but the Convert class doesn't seem to have anything to offer except exceptions.
Are there any that can return a bool for me to check?
To be clear, I'd like to avoid doing this
TextEdit amountBox = sender as TextEdit;
if (amountBox == null)
return;
try
{
Convert.ToInt32(amountBox.Text);
}
catch (FormatException)
{
e.Cancel = true;
}
in favor of something like this:
TextEdit amountBox = sender as TextEdit;
if (a开发者_如何学GomountBox == null)
return;
e.Cancel = !SafeConvert.TryConvertToInt32(amountBox.Text);
Thanks!
int.TryParse
is your friend...
TextEdit amountBox = sender as TextEdit;
if (amountBox == null)
return;
int value;
if (int.TryParse(amountBox.Text, out value))
{
// do something with value
e.Cancel = false;
}
else
{
// do something if it failed
e.Cancel = true;
}
... By the way, most of the privitive value types have a static .TryParse(...)
method that works very similar to the sample above.
精彩评论