I have some textboxes in my C# windows form application. I want to do the following:
inRed = Convert.ToInt32(tbRed.Text.ToString().Length < 0 ? tbRed.Text = "0" : tbRed.Text);
inGreen = Convert.ToInt32(tbGreen.Text.ToString().Length < 0 ? tbGreen.Text = "0" : tbGreen.Text);
inBlue = Convert.ToInt32(tbBlue.Text.ToString().Length < 0 ? tbBlue.Text = "0" : tbBlue.Text);
inCyan = Convert.ToInt32(tbCyan.Text.ToString().Length < 0 ? tbCyan.Text = "0" : tbCyan.Text);
inMagenta = Convert.ToInt32(tbMagenta.Text.ToString().Length < 0 ? tbMagenta.Text = "0" : tbMagenta.Text);
If the textbox doesn't have a value, enter a 0 and convert to integer, otherwise convert the value of the textbox to integer.
I am getting the following error for inCyan, where the textbox is empty:
Input string was not in a correct format.
How can I achieve what I am looking for?
Instead of Convert.ToInt32, use Int32.TryParse. This gives you feedback regarding if it was a valid integer. e.g.
String textboxValue = "1";
Int32 i;
if (!String.IsNullOrWhitespace(textboxValue) && // Not empty
Int32.TryParse(textboxValue, out i)) { // Valid integer
// The textbox had a valid integer. i=1
} else {
// The texbox had a bogus value. i=default(Int32)=0
// You can also specify a different fallback value here.
}
As a follow-up, String.IsNullOrWhitespace makes it easy to decipher if a value is supplied, but (depending on your .NET version) is may not be available (and you may only have String.IsNullOrEmpty.
If need be, the polyfill is something long the lines of:
Boolean SringIsNullOrWhitespace(String input)
{
return !String.IsNullOrEmpty(input) && input.Trim().Length > 0;
}
Also, if you find yourself trying to perform this parsing frequently, you could refactor it into a helper class:
public static class ConvertUtil
{
public Int32 ToInt32(this String value)
{
return ToInt32(value, default(Int32));
}
public Int32 ToInt32(this String value, Int32 defaultValue)
{
#if NET4
if (!String.IsNullOrWhiteSpace(value))
#else
if (!String.IsNullOrEmpty(value) && value.Trim().Length > 0)
#endif
{
Int32 i;
if (Int32.TryParse(value, out i))
{
return i;
}
}
return defaultValue;
}
}
// explicit
inRed = ConvertUtil.ToInt32(tbRed.Text, 0/* defaultValue*/);
// As extension
inRed = tbRed.Text.ToInt32(0/* defaultValue*/);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With