我的程序将选定的书籍添加到购物车(cartComboBox
),然后计算底部的运行总计(totalPriceLabel
)。我遇到类型的问题,因为它拉入一个字符串而不是转换为十进制。
我的问题是,放置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");
}
}