[英]input string was not in correct format c# displaying a price on a label
Im new to c# and im trying to display a price of a product on a label, however when i run the page i get the error " input string was not in correct format" i have set the price as float. 我是C#的新手,我试图在标签上显示产品的价格,但是当我运行页面时,出现错误“输入字符串的格式不正确”,我将价格设置为浮动价格。
this is the current code: 这是当前代码:
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);
}
}
}
} }
You get the error at 您在以下位置得到错误
String.Format("{0.0.00}", products.Price + "<br/>")
That's not a valid format string, you either have to use: 这不是有效的格式字符串,您必须使用:
String.Format("{0:0.00}", products.Price + "<br/>")
or 要么
String.Format("{0}", products.Price.ToString("0.00") + "<br/>")
As an aside, you can put the <br/>
also into the String.Format
for better readability: String.Format
,您还可以将<br/>
放入String.Format
以提高可读性:
String.Format("{0:0.00}<br/>", products.Price)
I think you want something like this: 我想你想要这样的东西:
Label lblPrice = new Label
{
Text = String.Format("{0:C}", products.Price + "<br/>"),
CssClass = "ProductsPrice"
};
Using {0:C) specifies that the string should be a Currency format. 使用{0:C)指定该字符串应为货币格式。
See: String format currency 另请: 字符串格式货币
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.