Visual C# Express - Parsing User Input (4th In A Series)
TextBox Accepts only Strings
There are four user input text boxes in the CompoundGrowth form of the InterestCalculator program, and all of them APPEAR to accept numeric; but in fact they do not. They all accept strings, for one simple reason. Strings are the only data accepted by the .net TextBox control. In fact the only way to read the contents of the TextBox control is via the "Text" property, which returns a string.
Parse Function to the Rescue
Since the Textbox control accepts only strings, the programmer is stuck with the problem of converting from a C# string type to a C# numeric type. There are in fact several methods for doing this using the .net class library, but in this article I will show you how to do it using the Parse function.
Nearly every numeric data type has a Parse function which operates on a string and converts it to a numeric data type. For example, the code to convert from a string to a double would look something like the following:
// Convert string in txtPrincipal TextBox to a double precision number mPrincipal= Double.Parse( txtPrincipal.Text);
That's all there is to it . . . except for one small problem. What happens when if someone types something like "1A3Y" into the txtPrincipal TextBox? Now we have a problem.
Recovering from Erroneous Inputs
It would easy to design forms if people always hit the right buttons and always entered the correct data. The challenge of designing and coding forms is to give them reasonable error recovery scenarios.
The .net class library supports a solution to the problem detecting and handling erroneous input. In addition to the Parse function there is a TryParse function associated with each numeric data type. The TryParse function does just what you would think, it tries to parse a text string and returns boolean true if it is able to and boolean false if it cannot.
Now the code, contained in the function ValidateInput looks more like this:
if (!double.TryParse(txtPrincipal.Text, out mPrincipal))
{ txtAmount.AppendText("Principal must be a number");
success = false; }
The same type test is repeated for each of the numeric text boxes in the form, and the function ValidateInput returns false if any of the tests fail.
In addition, as you can see above (or in your copy of downloaded code), an error message is printed to the user for each text box which does not validate properly; and the compounded investment value will not be displayed unless all four text box inputs validate.
If an error message is displayed, the user has the option of correcting the contents of the invalid TextBox(es) and resubmitting by pushing the "Calculate Amount" button again.
Other Options
Although this article did not discuss them, I would like to briefly mention two other options for doing the string to numeric conversion.
(1) Build the conversion into the TextBox, by inheriting the TextBox class and adding a text-to-numeric conversion property or method. That is a very elegant solution and would make a lot of sense if you were using a lot of numeric input text boxes.
(2) The Convert class contains methods to convert every base type to every other base type. The methods Convert.ToDouble and Convert.ToUInt64 could be used instead of double.TryParse and ulong.TryParse respectively; however these methods do not return the status of the conversion so the programmer would need to implement exception code to trap invalid input.
Summary
You can find a copy of the Interest Calculator Code on my Article Support Page.
The .net TextBox class allows only textual input, so the programmer needs a way to convert the string value of the TextBox to a numeric value. The TryParse function solves this problem with the additional bonus that it performs error checking and returns the boolean status of the conversion.
Related Tags: microsoft, convert, double, string, visual c#, parse, user input, tryparse, validate, textbox, ulong
Sam Mela runs a math tutoring business in Springfield Virginia. His web site is http://www.WeekendSuccess.com
Your Article Search Directory : Find in ArticlesRecent articles in this category:
- Free Internet Security Software from Google
Selecting the internet security software for your computer can be a daunting task for most home user - Home Key Logger - Track Computer Activity
What goes through your mind when you think about a home key logger? Do you think about a rogue progr - Computers and Electronics Have Changed The Way We Live
You push the on button and your monitor screen springs to life. Next, you use your mouse to bring up - What PacketShaper Can Do For You?
What is PacketShaper?It is an application-intelligent traffic management system which delivers predi - Key Logger Software for Your Computer
One thing that many of us are concerned about is the safety of our children and what happens when th - Keep Your PC Healthy With Computer Tips & Tricks
Everybody just has to have a computer these days. Life without a computer is unimaginable. I am sure - Antivirus - What is a Computer Virus?
Before understanding what a computer virus is, it is necessary to understand what a virus in when it - Gibberish Spam Email - Why Do Spammers Send It?
We have all seen many spam emails that just make no sense. They contain pure gibberish in the subjec - Your Children And The Internet - 5 Tips To Keep Your Children Safe While They Are Online
If your children are on the Internet you may be concerned about their safety. We hear stories regula - How To Compare Residential VOIP Offerings
Many people are turning to VOIP phone for several different reasons, the biggest reason being cost.
Most viewed articles in this category:
- Experience the new Microsoft Zune and Future Technology with Bill Gates at CES Keynote
After the demonstration of Windows Vista by Bill Gates at the CES keynote, Robbie Bach, President of - Internet Connection Sharing in Windows XP
This articles explains in detail how to set up a small network at home so you can share your Interne - Nortel VPN Client Overview
The Nortel VPN Client creates the secure connection for VPN users into a private network. Once you l - Computer Phobias
Years ago around the end of January I would develop Chinophobia (fear of snow). Maybe it was becaus - iPod Stuff: How To Set Your iPod's Alarm Clock
The good thing about the iPod alarm clock feature is that you can wake up with the tune of your favo - CCTV: the story continues
CCTV – Closed Circuit Television – for some time at least has been used by various gover - Why Someone Stole My Mobile Phone
Not so long ago my mobile phone was stolen. I kept asking why I was the one who got targeted, especi - Office printers: introduction to technology and types
With every bit of information transfer and manipulation going digital these days, almost the entire - Computer hardware simplified
Computer Hardware is a comprehensive term which refers to all the physical parts of a computer inclu - Cordless phone technology: a brief history
Cordless Phones – as the term suggests – is a phone sans any cord. Instead the handset c