Click here to Skip to main content
15,884,176 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

InputBox: A simple user input dialog

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
25 Dec 2011CPOL 6.6K  
You have introduced a Globalization / Regional problem by requiring the default value to be a string.double? value = InputBox.GetDouble("xyz", "1.0"); //Note the dotdouble? value2 = InputBox.GetDouble("xyz", "1,0"); //Note the commaOne of these two will fail, but not on every machine or...

You have introduced a Globalization / Regional problem by requiring the default value to be a string.


C#
double? value = InputBox.GetDouble("xyz", "1.0"); //Note the dot
double? value2 = InputBox.GetDouble("xyz", "1,0"); //Note the comma

One of these two will fail, but not on every machine or country or even on the the same line. The 'ToString()', 'Parse()', and 'string.Format()' methods are running under the regional settings of the thread. Which is by default the same as the RegionalSettings for the logged on user, but it does not have to be. For more information, read the helpfile for these functions.


We can elevate the pain for the default value by making the default value the same type as the result; this helps greatly, unless string is the native value for the default, in which case you might need two versions of the method.


Simple fix:


C#
public static double? GetDouble(string caption, double?defaultValue)
{
    ClearLastError();
    // The ToString will convert the value to the Culture of the thread.
    // If you run Code Analisys on this line, it will tell you that
    // you should be more explicit with the culture, I'll leave that as homework. ;-)
    using (InputForm inForm = new InputForm(caption, defaultValue.ToString()))
    {
[edit: and the rest]
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Netherlands Netherlands
Doing that 'computer thing' ever since the C64.

Sometimes I feel that being a programmer is much like being a doctor: You just have to know everything and if you don't, something dies.

Either being an application or a patient.

Oddly enough, more people care about the death of their application, than the massacre of people...

Comments and Discussions

 
-- There are no messages in this forum --