[英]C# Where to place decimal TryParse
我的程序將選定的書籍添加到購物車 ( cartComboBox
),然后計算底部的運行總數 ( totalPriceLabel
)。 我的類型有問題,因為它拉入一個字符串而不是轉換為十進制。
我的問題是,放置decimal.TryParse
語句的最佳位置在decimal.TryParse
,如果是這樣,是否會刪除任何decimal.Parse
語言?
private void selectionListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if(selectionListBox.SelectedItem.ToString() == "Visual Basic")
{
this.bookPictureBox.Image = Image.FromFile("visualbasic.jpg");
priceLabel.Text = 119.99.ToString("c");
}
else if(selectionListBox.SelectedItem.ToString() == "Java")
{
this.bookPictureBox.Image = Image.FromFile("java.jpg");
priceLabel.Text = 109.99.ToString("c");
}
}
private void addCartButton_Click(object sender, EventArgs e)
{
try
{
decimal totalPrice;
decimal cost = 0;
// if(decimal.TryParse(priceLabel.Text, out totalPrice)?
if (cartComboBox.Items.Contains(selectionListBox.SelectedItem))
{
MessageBox.Show("Duplicates not allowed.");
}
else
{
//if(decimal.TryParse(priceLabel.Text, out totalPrice)?
cartComboBox.Items.Add(selectionListBox.SelectedItem);
totalPrice = decimal.Parse(priceLabel.Text);
cost += totalPrice;
totalPriceLabel.Text = cost.ToString("c");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message); //input string was not in correct format
}
}
我會在 else 語句中使用它。 我假設您只想添加具有有效價格的項目。
else
{
if(decimal.TryParse(priceLabel.Text.Replace("$",""), out totalPrice))
{
cartComboBox.Items.Add(selectionListBox.SelectedItem);
cost += totalPrice;
totalPriceLabel.Text = cost.ToString("c");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.