Hey everyone! Happy New Year!

I am trying to hone my programming skills by writing simple applications. I created a very simple currency converter program (hard-coded exchange rates....so nothing special). I first created it as a console app, and then in WPF.

Anyway, I ran into an issue with the textbox that takes input. I wasn't sure what would be the best way to keep letters from being entered. After looking online at regular expressions, I wrote a basic regex using an if statement to keep invalid input from being entered:

[a-zA-Z+!@#$%^&*()]

If the input has letters, then a messagebox is prompted (after pressing a button) and I have that button's method set to clear the textbox.

*****So basically, the program works 100% properly, but I was wondering if using Regex was the "best" move as opposed to trying to implement a try-catch, which quite honestly, I do not understand how to use completely. I was reading something about SQL queries vs. LINQ (speed of returning results), etc. and was wondering if regex vs. try-catch was similar.

*If anyone wants to see some of the code, just let me know which parts you want to see or the whole program.

Recommended Answers

All 3 Replies

You are trying to ensure that only numbers are entered (with the appropriate decimal specifier, if needed). Regex and Try/Catch are slow ways to do this, just use TryParse:

double value = 0.0;
if (Double.TryParse(myTextBox.Text, out value)) {
    // it is convertable to a double, so we are good and the value is in 'value'
} else {
    // it is not convertable to a double: Error, danger Will Robinson!
}

of course you can use other types (Int32, Decimal, etc.) just replace the appropriate types :)

or switch to a masked text box where you can set a mask to filter out letters

Ah, TryParse looks like a better way! Thanks Momerath!

Tinstaafl, thanks for suggesting the masked textbox. I didn't know about that functionality.

Thanks for the quick responses. Sorry for getting back to you all so late.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.