Incorrect Format

 

Here's the scenario: I'm building a basic 3-layer Web application for a client with business and data layers. Queries are performed in stored procedures, just basic ADO.NET. The table I am attempting to insert a record into has a range a field types such as strings, ints, decimals, etc.

If the user is entering integer or decimal values via texboxes, which is usually the case, then you have to expect either no data or a string of possibly mal-formed data. You must filter out the mal-formed data with validation and/or convert the resulting input data to the expected database type.

If you have a database field called SquareFeet of type int and you attempt to insert the following in your code-behind insert method, you will probably see this error:

// Results in error message
AddSomething(int squareFeet)
{
    Convert.ToInt32(SquareFeetTxtBox.Text.Trim());   
}

 

You must be careful if you are trying to fetch, say, an int or decimal as input:

// Correct way if SquareFeet field is an int
int squareFeet
if (int.TryParse(squareFeetTxt.Text.Trim(), out squareFeet))
    squareFeet = Convert.ToInt32(squareFeetTxt.Text.Trim());
else
     squareFeet = 0;
// Now insert the value as part of the record

 

// Correct way if SquareFeet field is a decimal
int squareFeet
if (decimal.TryParse(squareFeetTxt.Text.Trim(), out squareFeet))
    squareFeet = Convert.ToDecimal(squareFeetTxt.Text.Trim());
else
     squareFeet = 0.0m;
// Now insert the value as part of the record

 

References

Refer to these links for the differences between Convert.ToInt, int.Parse and Int.TryParse:
http://dotnetperls.com/int-parse-conversion
http://dotnetperls.com/int-tryparse

Refer to this link for an explanation of the 0.0m decimal syntax:
http://msdn.microsoft.com/en-us/library/364x0z75(VS.80).aspx

Moral of the Story
If you are learning any language, your first priority must be to understand the types thoroughly. Resist the temptation to gloss over the grammar just to get to the fancy stuff! :-)

Tags: , ,

ASP.NET | C#



Comments (5) -

Lee Dumond
Lee Dumond United States
8/20/2009 2:44:51 PM #

I agree that using TryParse is usually better than using the coreresponding Parse method and handling the exception. However, the best way to handle this is to validate the input for the correct data type to begin with.

agrace
agrace United States
8/20/2009 3:00:12 PM #

Hiya Lee,
Yep, I have to agree with you - one can never underestimate the stupidity of the end user. Getting in their mindset must be as painful as trying to profile a serial killer!

Anthony Wink

Kelps
Kelps Brazil
8/23/2009 10:56:17 AM #

There is an even simpler way to do that, because you neglected one aspect of the TryParse methods: They already set the value for the out or ref parameters when the parse is valid. There is no need to call a Convert method for that. Here is an example:

This is the code you posted
#####################################################
// Correct way if SquareFeet field is an int
int squareFeet
if (int.TryParse(squareFeetTxt.Text.Trim(), out squareFeet))
    squareFeet = Convert.ToInt32(squareFeetTxt.Text.Trim());
else
     squareFeet = 0;
// Now insert the value as part of the record
#####################################################

This is a simpler version of the code with the same results
#####################################################
<p class="code">
int squareFeet = 0;
int.TryParse(squareFeetTxt.Text.Trim(), out squareFeet);
</p>
#####################################################

If the TryParse succeeds, squareFeet will have the inputed value. If it fails, squareFeet will remain unchanged (in this case with the value 0). If you need to perform anything else when TryParse succeeds of fails, just put the "if" back around it, otherwise you can ignore it.

This works for any TryParse I've used so far. Some use "out" parameters (when it is a primitive type like int, decimal or bool...) and the others use "ref", but they all work the same way.

agrace
agrace United States
8/23/2009 11:05:56 AM #

Thanks Kelps, much neater Smile

traslochi internazionali milano
traslochi internazionali milano United States
11/28/2009 8:02:35 AM #

Admiring the time and effort you put into your article and detailed information you offer.

Pingbacks and trackbacks (3)+