Search code examples
c#.netparsingentitiesformatexception

I'm getting a FormatException even though my C# code parses correctly


I have a line of code that runs as a part of my Save button. The Save button stores some data into my database. Part of the data that gets saved is each item's rank. I assign each item a rank in the front end and it gets parsed out and stored into the database. Here is the problematic code:

using(CCGEntities db = new CCGEntities())
{
    foreach(DataGridItem dgi in uxCustomSetList.Items)
    {
        int dataKey = (int)uxCustomSetList.DataKeys[dgi.ItemIndex];
        var temp = db.CustomSetAwardSets.FirstOrDefault(s => s.CustomSetAwardSetID == dataKey);
        temp.AwardSetComments = ((TextBox)dgi.FindControl("txtComments")).Text.Trim();
        temp.Rank =  Int32.Parse(((TextBox)dgi.FindControl("txtRank")).Text);
        db.SaveChanges();
    }
}

The problem is this line:

temp.Rank = Int32.Parse(((TextBox)dgi.FindControl("txtRank")).Text);

The rank for each item is saved into the database successfully but I'll get a FormatException error screen all the same. Any ideas what the problem is? The parsing is obviously working correctly if the data is being stored into the database, so why is it complaining about bad formatting? temp.Rank is an int? by the way.


Solution

  • In general, and especially when using input from a UI, using TryParse is a better idea than using Parse, as it is cleaner to check for errors (in my opinion) and gives the programmer a greater level of control over different possible input values.

    Your specific error is probably because the text property of your control is empty or null, and this would throw a FormatError exception on an int.Parse call.