繁体   English   中英

从列表框中取出数据时,如何从C#中的字符串计算值?

[英]How do I calculate a value from a string in C# when taking data out of a list box?

我有一个表单程序,需要帮助。 我需要从一个字符串计算总数。 在此程序中,我有一个五金店,在框中列出了物品。 用户选择项目,然后选择数量。 收据列表框显示项目。 我有这部分就好了。 但是,当我尝试计算框中的内容时,出现错误。 计算完后,我需要在对话框中输入美元金额来计算更改。 任何人都可以帮助这个新手吗?

namespace HardwareStore
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();

            ProductBox.Items.Add(new Hardware(){ItemNo = 1010, ProdName = "Hammer         ", Price = (decimal)14.99d });
            ProductBox.Items.Add(new Hardware(){ItemNo = 1056, ProdName = "Bag of Nails   ", Price = (decimal)19.99d });
            ProductBox.Items.Add(new Hardware(){ItemNo = 2001, ProdName = "Saw               ", Price = (decimal)29.99d });
            ProductBox.Items.Add(new Hardware(){ItemNo = 2005, ProdName = "Chainsaw       ", Price = (decimal)69.99d });
            ProductBox.Items.Add(new Hardware(){ItemNo = 3090, ProdName = "Ladder          ", Price = (decimal)109.99d });
        }

        private void frmMain_Load(object sender, EventArgs e)
        {

        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
           for (int i = 0; i < int.Parse(txtQuantity.Text); i++)
           ReceiptBox.Items.Add(ProductBox.Items[ProductBox.SelectedIndex]);
        }

       private void ReceiptBox_SelectedIndexChanged(object sender, EventArgs e)
        {
           int total = 0;
           //foreach (Hardware Current in ReceiptBox.Items) total += Current.

           //double subtotal = Math.Round((ReceiptBox.Items), 2);
           //double tax = Math.Round((subtotal * .075), 2);
           //double total = subtotal + tax;
        }

           private void btnCalculate_Click(object sender, EventArgs e)
        {
           //lblSub.Text = "$" + subtotal.ToString();
           //lblTax.Text = "$" + tax.ToString();
           //lblTotal.Text = "$" + total.ToString();

           lblSub.Visible = true;
           lblTax.Visible = true;
           lblTotal.Visible = true;
        }

       private void btnChange_Click(object sender, EventArgs e)
        {
           //MessageBox.Show("Change Due: $ ",);

        }
    }
}

您需要将string转换为double 尝试这个:

double subtotal = Math.Round(double.Parse(ReceiptBox.Items), 2);

ReceiptBox无法知道存储在其中的对象的类型。 您将需要这样施放

var subTotal = ReceiptBox.Items.Cast<Hardware>().Sum(item => item.Price);

对WinForms不太熟悉,但是看起来更好的方法是利用ListBox.DataSource属性

这是关于这个问题的stackoverflow线程

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM