如何使用数学方法从列表框的选择中更新标签框

问题描述 投票:0回答:1

所以我的表单中有2个列表框。 Listbox1包含具有价格的不同类型的项目,Listbox2包含您要购买的项目数量。如何更新价格标签,以便当我从每个列表框中选择两个选项时,它会更新标签并给我一个价格。这是一个示例,可以帮助您更好地理解。

我在ListBox1中选择了$ 1.50巧克力曲奇,然后在ListBox2中选择了1个Cookie。因此,我希望我的priceLabel更新为$ 18.00。我该怎么办?

截至目前,我已经尝试在listBox1_SelectedIndexChanged方法中创建一些代码,但是返回了以下三个值...$0.00...$2.00... $4.00

这是我的代码:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            double index = listBox1.SelectedIndex;
            double index2 = listBox2.SelectedIndex;
            double total = index * index2;
            label9.Text = total.ToString("C");
        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void label9_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            const int ESTIMATED_ARRIVAL = 3;
            label10.Text = monthCalendar1.SelectionStart.AddDays(ESTIMATED_ARRIVAL).ToShortDateString();
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
c# winforms
1个回答
0
投票

您的代码中的问题是“ .SelectedIndex”属性仅返回列表框中当前所选项目的0索引位置。这就是计算错误的原因。

我想建议使用“ .SelectedItem”属性。因为它返回所选项目本身而不是其位置。因此,您的项目包含文字双精度值,则计算将成功。

© www.soinside.com 2019 - 2024. All rights reserved.