更新时间:2023-09-11 11:19:58
试试:double 价格;
if (!double.TryParse(txtPrice.Text, out price))
{
// 向用户报告输入问题。
...
return ;
}
product.Price = price;如果Price是一个整数 - 它可能不应该是 - 那么试试:
double 价格;
if (!double.TryParse(txtPrice.Text, out price))
{
// 向用户报告输入问题。
...
return ;
}
product.Price =( int )价格;永远不要使用Convert.To ...来处理用户输入:它总是在坏值上抛出异常,用户总是会犯错误。如果您填写了包含大量数据的表单,那么应用程序会因为您键入,而不是。而崩溃。你会非常恼火 - 所以让用户犯错并让他们纠正错误!
嗯。我一直在想,因为文本框名称是txtPrice,我想知道该框是否持有货币格式的字符串(£12.30)。如果是这种情况,请尝试按照以下示例System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo( en-GB);
string txtPrice = £12.30;
double 价格;
double .TryParse(txtPrice,System.Globalization.NumberStyles.AllowThousands |
System.Globalization.NumberStyles.AllowDecimalPoint |
System。 Globalization.NumberStyles.AllowCurrencySymbol,provider, out price);
product.Price = price;
输出:12.3
如果价格是整数
product.Price =( int )价格;
输出:12
private Product CreateProduct() { Product product = new Product(); product.Name = txtName.Text; product.Price = Convert.ToDouble(txtPrice.Text); product.TypeID = Convert.ToInt32(ddlType.SelectedValue); product.Description = txtDescription.Text; product.Image = ddlImage.SelectedValue; return product; }
What I have tried:
I've tried Convert.ToInt32(txtPrice.Text);, but that doesnt work either
Try:double price; if (!double.TryParse(txtPrice.Text, out price)) { // Report input problem to user. ... return; } product.Price = price;If Price is an integer - and it probably shouldn't be - then try:
double price; if (!double.TryParse(txtPrice.Text, out price)) { // Report input problem to user. ... return; } product.Price = (int) price;Never use Convert.To... to handle user input: it always throws an exception on bad values, and users make mistakes all the time. If you had filled out a form with a whole bunch of data, and the app then crashed because you types "," instead of "." you'd be pretty annoyed - so allow users to make mistakes and get them to correct them!
Hmmmmm. I been thinking, since the Textbox name is txtPrice, I was wondering if the box is holding string with currency format like (£12.30). If that the case, try follow the below exampleSystem.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-GB"); string txtPrice = "£12.30"; double price; double.TryParse(txtPrice, System.Globalization.NumberStyles.AllowThousands | System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowCurrencySymbol, provider, out price); product.Price = price;
Output: 12.3
if price is an integerproduct.Price = (int)price;
Output: 12