【问题标题】:Set double as a Label in a GridView在 GridView 中将 double 设置为 Label
【发布时间】:2016-05-26 00:17:17
【问题描述】:

我正在创建一个购物车。我有一个包含所有产品的 GridView,我有一个更新按钮,单击该按钮时,我想获取价格列中的值并将其与数量 TextBox 中的输入值相乘,并将其显示在 ItemTotal 标签中。我的 lblPrice 的 SQL 输入是十进制形式,但是它在 gridview 上显示为 $_.00。我一直遇到 lblPrice 的格式异常。我想知道是否有办法将 lblPrice 转换回小数但仍将其显示为 gridview 上的价格?

ShoppingCart.aspx

<asp:TemplateField HeaderText="Price">
    <ItemTemplate>
        <asp:Label ID="lblPrice" runat="server" Text='<%# Bind("Price")%>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
    <ItemTemplate>
        <asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox>
        <asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer"
        ControlToValidate="txtQuantity" ErrorMessage="Value must be a whole number" ForeColor="Red" />
    </ItemTemplate>
</asp:TemplateField>

ShoppingCart.aspx.cs

protected void btnUpdate_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in gvProductsList.Rows)
    {
        double lblPrice = Convert.ToDouble(((Label)row.FindControl("lblPrice") as Label).Text);//convert value of lbl to double
        int txtQuantity = int.Parse(((TextBox)row.FindControl("txtQuantity") as TextBox).Text);//convert value of textbox to int
        Label lblItemTotal = (row.FindControl("lblItemTotal")) as Label;//find lblItemTotal label in each row
        lblItemTotal.Text = Convert.ToString(lblPrice * txtQuantity);
    }
}

【问题讨论】:

  • 听起来你走在正确的道路上。什么不工作?
  • 我收到一个 System.FormatException,指出“输入字符串的格式不正确”。对于双 lblPrice = Convert.ToDouble(((Label)row.FindControl("lblPrice") as Label).Text);
  • 该标签的示例值是什么,lblPrice
  • 您应该在调试模式下运行,然后检查lblPrice 中的文本(鼠标悬停或使用shift+F9 并粘贴((Label)row.FindControl("lblPrice") as Label).Text 并按revaluation
  • 在 SQL 上设置为十进制,示例为 3,但我在 gridview 上将其格式化为 $3.00。

标签: c# asp.net gridview


【解决方案1】:

在cmets中经过一番讨论,我们发现问题出在这一行:

double lblPrice = Convert.ToDouble(((Label)row.FindControl("lblPrice") as Label).Text);

标签的价值约为 3.00 美元。转换为双倍失败。这是因为字符串包含一个美元符号,它不是一个有效的数字。

您可以通过Parse 方法将其转换回小数,并传入适当的NumberStyle - 在本例中为货币。

Label lblPrice = (Label)row.FindControl("lblPrice");
decimal price = decimal.Parse(lblPrice.Text, NumberStyles.Currency);

您可能需要查看TryParse,以便更好地处理错误。

确保包含 Globalization 命名空间以使用 NumberStyles。

using System.Globalization;        

【讨论】:

  • 我试过这个,我得到一个错误,说 NumberStyles 在当前上下文中不存在
  • @Jamie 然后将命名空间 System.Globalization 添加到您的 .cs 文件中:using System.Globalization;
  • 谢谢你,范。是的,请确保添加 Globalization 命名空间。我已更新我的答案以包含此信息。
  • 感谢您的回复!我现在有一个错误 lblItemTotal.Text = Convert.ToString(lblPrice * txtQuantity); “运算符'*'不能应用于'System.Web.UI.WebControls.Label'和'int'类型的操作数”你知道如何调整它以便它可以进行乘法吗?
  • 不客气!我相信也有解决方案。在 StackOverflow 上,最好一次只回答一个问题。尝试自己找出问题所在,如果仍然有问题,请随时写下另一个问题,有人可能会帮助您。
猜你喜欢
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多