C# 无法从文本框中获取值
我想做的是从下面的代码中获取总价文本框的值,然后声明它:C# 无法从文本框中获取值,c#,textbox,converter,C#,Textbox,Converter,我想做的是从下面的代码中获取总价文本框的值,然后声明它: private void UpdateTotalBill() { decimal vat = 0; decimal TotalPrice = 0; long TotalProducts = 0; foreach (DataListItem item in dlCartProducts.Items) { Label PriceLa
private void UpdateTotalBill()
{
decimal vat = 0;
decimal TotalPrice = 0;
long TotalProducts = 0;
foreach (DataListItem item in dlCartProducts.Items)
{
Label PriceLabel = item.FindControl("lblPrice") as Label; // get price
TextBox ProductQuantity = item.FindControl("txtProductQuantity") as TextBox; // get quantity
Int64 priceLabel, productQuantity;
bool conversionResult = Int64.TryParse(PriceLabel.Text, out priceLabel);
if (!conversionResult) continue;
conversionResult = Int64.TryParse(ProductQuantity.Text, out productQuantity);
if (!conversionResult) continue;
decimal ProductPrice = priceLabel * productQuantity; //computation fro product price. price * quantity
vat = (TotalPrice + ProductPrice) * 0.12M; // computation for vat
vat = Math.Round(vat, 2);
TotalPrice = TotalPrice + ProductPrice;
TotalProducts = TotalProducts + productQuantity;
}
Label1.Text = Convert.ToString(vat);
txtTotalPrice.Text = Convert.ToString(TotalPrice + 40.0M + vat); // add vat + 40 delivery charge to total price
txtTotalProducts.Text = Convert.ToString(TotalProducts);
}
并通过“小数金额=?”读取:
我试过这行代码:
decimal amount = Convert.ToDecimal(txtTotalPrice);
但它给了我一个错误的说法:
'System.Web.UI.WebControls.TextBox' to type 'System.IConvertible'.
非常感谢您的帮助。您正在尝试将文本框组件(而不是它包含的文本)转换为十进制。一个简单的更改将解决此问题:
decimal amount = Convert.ToDecimal(txtTotalPrice.Text);
小数金额=转换为小数(txtTotalPrice)
这一行实际上试图将Textbox控件转换为十进制
您需要像在页面加载期间一样使用“Text”属性。
此外,建议始终使用TryParse()而不是显式转换来处理运行时转换错误
decimal.TryParse(TextBox1.Text,out decimal_val)
例如,它只是我提到的一个变量名。
decimal amount = Convert.ToDecimal(txtTotalPrice.Text);