C# How to trap a wrong value updated in a GridView

Here is a small routine I had to develop in order to solve a problem about editing an integer value in a grid.

How to trap the error is the user put a letter instead of an integer and click update?

NameSpace

First of all I’m using collections, so we must import the relevant namespace

using System.Collections;

 

Grid Sample code



	
		
		
		
		
			
			
			
		
		
			
			
			
		
		
			
			
		
		
			
			
			
		
		
		
	

	


C# Code on RowUpdating grid event / Column QUANTITE_COMMANDE


protected void grdCart_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
	string strQty = "";
	DictionaryEntry ColEntry;

	//Browse the new values and save them in a collection (key / value)
	foreach (DictionaryEntry entry in e.NewValues)
	{

		if (entry.Key.ToString() == "QUANTITE_COMMANDE") //Corresponding to Datafield in your Grid
		{
			strQty = entry.Value.ToString();
			ColEntry.Key = entry.Key;
			ColEntry.Value = entry.Value;
		}

	}

	//Isolate the new value
	int intQty;

	// Try to convert the new value to integer
	try
	{
		intQty = int.Parse(strQty);
	}
	// If conversion fails then go back to the old value
	catch
	{
		intQty = int.Parse(e.OldValues[ColEntry.Key].ToString());
	}

	// Set the Quantity (old or new) to the new value in order to update it
	e.NewValues[ColEntry.Key] = intQty;

}