在GridView编辑中,“输入字符串格式不正确”

本文关键字:字符串 格式 不正确 输入 GridView 编辑 | 更新日期: 2023-09-27 18:03:40

我正在做我的第一个asp.net项目,似乎无法通过这个错误。下一步是计算两个值之间的差异(每个值在一个单独的网格视图中),并在文本框中显示差异。为了调试,我有一个文本框来显示每个值,所以现在有3个文本框。其中一个值是在一个可编辑的网格视图,当我点击编辑,我得到以下例外:

系统。FormatException发生Message=输入字符串不在正确的格式。源= mscorlib加:在System.Number。字符串字符串,NumberStyles选项,NumberBuffer&NumberFormatInfo info,布尔值parseDecimal)在System.Number。ParseDecimal(字符串值,NumberStyles选项,NumberFormatInfo numfmt)在System.Decimal。Parse (String s)在caremaster.caremaster。FieldDetailsGridView_RowDataBound(对象发送者,GridViewRowEventArgs e) in M:'My Documents'file.cs:line 48
InnerException:

下面是一个代码示例:
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();
}

现在我正在检索GridView_RowDataBound上的数据。我想我在gridview事件的差异之间感到困惑。由于单击"编辑"时发生此错误,我应该在RowDataEditing中检索推荐值吗?

下面是一些额外的细节:

decimal recommend; 
decimal applied;

提前感谢您的批评和指导。

在GridView编辑中,“输入字符串格式不正确”

使用Decimal.TryParse方法

if(!String.IsNullOrEmpty(e.Row.Cells[4].Text))
 decimal.TryParse(e.Row.Cells[4].Text,out recommend);

错误很明显:decimal.Parse无法转换e.Row.Cells[4]中的任何值。它的价值是什么?

试着这样做:

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();
 }