【发布时间】: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。