Reputation: 31
I am working on my first asp.net project and can't seem to get past this error. The next step is to calculate the difference between two values (each in a separate gridview) and display the difference in a textbox. For debugging I have a textbox to display each value, so right now there are 3 textboxes. One of the values is in an editable gridview, when I click edit I get the following exception:
System.FormatException occurred Message=Input string was not in a correct format. Source=mscorlib StackTrace: at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt) at System.Decimal.Parse(String s) at caremaster.caremaster.FieldDetailsGridView_RowDataBound(Object sender, GridViewRowEventArgs e) in M:\My Documents\file.cs:line 48
InnerException:
Here is a code sample:
protected void TotalNGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string totNUnits = e.Row.Cells[0].Text;
unitsN.Text = totNUnits;
applied = decimal.Parse(e.Row.Cells[0].Text.ToString())
}
}
protected void FieldDetailsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string recNUnits = e.Row.Cells[4].Text;
recomN.Text = recNUnits;
recommend = decimal.Parse(e.Row.Cells[4].Text.ToString()); // exception thrown
calcNtoApply();
}
}
protected void calcNtoApply()
{
decimal final;
final = recommend - applied;
finalN.Text = final.ToString();
}
Right now I am retrieving the data on GridView_RowDataBound
. I think I'm confused between the differences in gridview events. Since this error happens when "edit" is clicked, should I be retrieving the value for recommend in RowDataEditing
?
Here are some additional details:
decimal recommend;
decimal applied;
Thanks in advance for any criticism and guidance.
Upvotes: 2
Views: 4609
Reputation: 94645
Use Decimal.TryParse
method.
if(!String.IsNullOrEmpty(e.Row.Cells[4].Text))
decimal.TryParse(e.Row.Cells[4].Text,out recommend);
Upvotes: 2
Reputation: 102408
The error is pretty clear: decimal.Parse
is not able to convert whatever value you have in e.Row.Cells[4]
. What's the value there?
Try doing like this:
if (e.Row.RowType == DataControlRowType.DataRow)
{
string recNUnits = e.Row.Cells[4].Text;
recomN.Text = recNUnits;
if(!String.IsNullOrEmpty(e.Row.Cells[4].Text))
{
recommend = decimal.Parse(e.Row.Cells[4].Text);
}
calcNtoApply();
}
Upvotes: 0