> C# newbie after migrating from VB. I wish to have
> only valid numbers entered into a txtbox . i.e only
> one decimal point.
There's much more to it than that. Some foreign cultures use ","
instead of "." as their decimal separator, and there's the issue of
negative numbers (again, not always "-"), and apart from symbology
you've got the question of maximum length, e.g. a string of nine
thousand 8s isn't going to produce a number in any acceptable range.
Additionally, a textbox can change in ways that aren't detected by the
KeyPress event: for example, you might paste text from the Clipboard
using only the mouse.
Your best bet is probably to let them type anything in the textbox,
but handle the TextChanged event and disable the actual OK button - or
whatever they use to proceed - until something valid is in there, with
an appropriate warning displayed. (To test for a valid floating-point
number, use Convert.ToSingle: if it throws an exception [which you can
catch], the number is not valid.)
Eq.
trawlerman - 20 Aug 2006 22:27 GMT
> Your best bet is probably to let them type anything in the textbox,
> but handle the TextChanged event and disable the actual OK button - or
[quoted text clipped - 4 lines]
>
> Eq.
Yes , i think that sounds like a more logical approach, and i will
probably go down that road.
But for piece of mind i still need to find a solution.
Thanks for the advice
Colin Williams
Steve Barnett - 21 Aug 2006 08:24 GMT
>> Your best bet is probably to let them type anything in the textbox,
>> but handle the TextChanged event and disable the actual OK button - or
[quoted text clipped - 12 lines]
>
> Colin Williams
For pease of mind purposes only, how about:
private void textBox_TextChanged(object sender, EventArgs e)
{
string strText = textBox.Text;
string decimalPoint =
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
if (strText.IndexOf(decimalPoint) !=
strText.LastIndexOf(decimalPoint))
MessageBox.Show("Oops");
}
Steve
trawlerman - 21 Aug 2006 13:26 GMT
Thanks Steve,
A peace of my mind is now at piece.
Colin
Ben Newsam - 21 Aug 2006 15:49 GMT
>A peace of my mind is now at piece.
You may now rest in peas.