输入字符串的格式不正确 c# 在标签上显示价格

input string was not in correct format c# displaying a price on a label

我是 C# 的新手,我试图在标签上显示产品价格,但是当我 运行 页面时,我收到错误消息“输入字符串的格式不正确” 我已将价格设置为浮动价格。

这是当前代码:

using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using WebApplication1.DataAccess;


namespace WebApplication1
{
public partial class Store : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GenerateControls();
    }

    private void GenerateControls()
    {
        ArrayList productsList = Connection.GetProductsByType("%");

        foreach (Products products in productsList)
        {
            Panel productPanel = new Panel();
            Image image = new Image { ImageUrl = products.Image, CssClass = " ProductsImage" };
            Literal literal = new Literal() { Text = "<br/>" };
            Literal literal2 = new Literal() { Text = "<br/>" };
            Label lblName = new Label { Text = products.Name, CssClass = "ProductsName" };
            Label lblPrice = new Label
           {
              Text = String.Format("{0.0.00}", products.Price + "<br/>"),
              CssClass = "ProductsPrice"
           };

            TextBox textBox = new TextBox
            {
                ID = products.Id.ToString(),
                CssClass = "ProductsTextBox",
                Width = 60,
                Text = "0"
            };

            RegularExpressionValidator regex = new RegularExpressionValidator
            {
                ValidationExpression = "^[0-9]*",
                ControlToValidate = textBox.ID,
                ErrorMessage = "Please enter number."
            };

            productPanel.Controls.Add(image);
            productPanel.Controls.Add(literal);
            productPanel.Controls.Add(lblName);
            productPanel.Controls.Add(literal2);
            productPanel.Controls.Add(lblPrice);
            productPanel.Controls.Add(textBox);
            productPanel.Controls.Add(regex);

            pnlProducts.Controls.Add(productPanel);

        }
    }
}

}

您在

收到错误
String.Format("{0.0.00}", products.Price + "<br/>")

这不是有效的格式字符串,您要么必须使用:

String.Format("{0:0.00}", products.Price + "<br/>")

String.Format("{0}", products.Price.ToString("0.00") + "<br/>")

顺便说一句,您可以将 <br/> 也放入 String.Format 中以获得更好的可读性:

String.Format("{0:0.00}<br/>", products.Price)

我想你想要这样的东西:

 Label lblPrice = new Label
 {
     Text = String.Format("{0:C}", products.Price + "<br/>"),
     CssClass = "ProductsPrice"
 };

使用 {0:C) 指定字符串应为货币格式。

参见:String format currency