【问题标题】:Input string was not in a correct format with TemplateField in a GridViewGridView 中的 TemplateField 的输入字符串格式不正确
【发布时间】:2014-05-10 06:39:39
【问题描述】:

我在 GridView 控件中有一个如下所示的模板字段。

<asp:TemplateField HeaderText="Total" SortExpression="CYTotal">            
            <ItemTemplate>
              <asp:Label ID="lblCYTotal" runat="server" MaxLength="20" Width="30" ReadOnly ="true"
                Text = '<%# Bind("CYTotal","{0:#,##0}") %>' Font-Names="Tahoma" Font-Size="8pt"> </asp:Label>
            </ItemTemplate>        
               <HeaderStyle Width="30px" Font-Names="Tahoma" Font-Size="8pt"/>
              <ItemStyle Width="30px" HorizontalAlign="Right" />    
          </asp:TemplateField>

我在RowDataBound事件的模板字段内设置标签的格式如下所示

if (accountTextBox.Text != "Gross Margin")
                {                 
                    lblCYTotal.Text = String.Format("{0:$#,##0}", Convert.ToDecimal(lblCYTotal.Text));
}
else if (accountTextBox.Text == "Gross Margin")
                {                 
                    lblCYTotal.Text = String.Format("{0:P0}", Convert.ToDecimal(lblCYTotal.Text));
}

然后,在 RowUpdating 事件中,我使用以下代码,但它给了我错误“*输入字符串格式不正确*t”。 我尝试使用下面的“替换”删除“%”符号,但没有运气。我还尝试使用 NumberStyles.Currency 和 NumberStyles.Float。

decimal currency = decimal.Parse(lblCYTotal.Text.Replace("%",""), NumberStyles.Any);

任何帮助将不胜感激!!!

【问题讨论】:

  • 为什么不替换$?因为从您的代码看来,您的文本框中可能有 $ 。如果是,那么它肯定会给你一个例外。
  • 感谢 Manish,我应该提到我确实尝试替换 $ 和 % 但仍然遇到相同的错误。
  • 好的,但是你没有提到你在哪一行出错以及出错时文本框的文本是什么。

标签: c# asp.net forms gridview web


【解决方案1】:

好的,我发现了问题。从数据库中提取的行之一中有一个 NULL 值。我让它显示为零(使用 ISNULL 函数)并且错误消失了。我不确定这是否是最好的方法,但我想不出任何其他方法。

我在后面的代码中有 if 语句来检查 NULLS 并且只格式化非空值,但它不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多