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! :-)

kick it on DotNetKicks.com

Tags: , ,

ASP.NET | C#