Validate a textbox entry c# using tryParse

In strongly typed language, there is no room for error when a user enters data that is expected to be put into a data storage system.

For example, I need to covert an input from textbox1 that is supposed to be a number to be used in a total:

 int fundAmt = Convert.ToInt32(TextBoxPersonalFundAmt.Text);

 

If the user enters unexpected non numeric characters, this conversion will fail and make your app error out. Instead of directly trying to convert, we can cast a Boolean on our input data using TryParse to parse the number into an integer…

bool isNumeric = int.TryParse(TextBoxPersonalFundAmt.Text, out n);

Now we can validate the input and perform the necessary calculations with the numbers.

 

int fundAmt;
bool isNumeric = int.TryParse(TextBoxPersonalFundAmt.Text, out fundAmt);
       if (!isNumeric)
            {
              errInfo += "Error: Its not a valid number in the amount box ";
               lblLogErr.Text = errInfo;
                 pageValid = false;
                } else
                {
                    // calculate the total
                }

 

Another good example is the date field. A user is expected to enter  a valid date for their birthday. There are many ways that a user would normally express that date. We of course use a client side validation to ensure that the format is entered correctly, but we need to have a server side validation of that data as well.

 

DateTime SponsorSigDate;
            if(!DateTime.TryParse(TextBoxSponsorDate1.Text, out SponsorSigDate))
            {
               
                pageValid = false;
                errInfo += "Error: Enter a valid date. ";
            }

Leave a Reply