Thursday, December 21, 2017

WinForms TextBox Get as Double or Integer

I always end up returning to Windows Forms when I want to code some tool or prototype an idea. This time I just want to share two extension methods for retrieving the contents of a TextBox as an Integer or a Double.

public static double AsDouble(this TextBox textBox)
{
 var s = textBox.Text.Replace(",", ".").Trim();
 return double.TryParse(s, out var d) ? d : double.NaN;
}
public static int AsInt(this TextBox textBox)
{
 var s = textBox.Text.Trim();
 return int.TryParse(s, out var i) ? i : 0;
}

The colon to period replacement is to ensure that Swedish formatting works with the default parser. No guarantee that it will work with all cultures.


All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment, not required but appreciated! :)

Hope this helps someone out there!
Until next time, Challenge yourself to do something new

No comments:

Post a Comment