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:

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

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.

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.