显示列表框内所有项目的总和

时间:2017-11-20 15:35:10

标签: c# winforms listbox

是否可以在ListBox中总结所有商品的价格?我有这个ListBox来显示来自DataGridView的项目,它们的每个价格都在priceTextBox中。请参考下面的图片。

enter image description here

我想要做的是显示所有商品价格的总和,并将其显示在totalTextBox

我已经完成了此代码,但我认为这不起作用。

private void menuListBox_SelectedValueChanged(object sender, EventArgs e)
    {
        int x = 0;
        string Str;

        foreach (DataGridViewRow row in menuDataGrid.Rows)  //this part displays the price of each item to a textbox so this is good.
        {         
            if (row.Cells[3].Value.ToString().Equals(menuListBox.SelectedItem.ToString()))
            {                   
                pricetxtbox.Text = row.Cells[5].Value.ToString();                                     
                break;
            }
        }

        foreach (string Str in row.Cells[5].Value.ToString().Equals(menuListBox.SelectedItem.ToString())) //now this is the part where I want to happen the adding the prices of all items in the listbox. this also gives me an error at row saying it doesn't exist in the context 
        {
            x = x + Convert.ToInt32(Str);
            totaltxtbox.Text = x;
        } 
    }

非常感谢任何帮助!谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个......

Func<string, DataGridViewRow> getRow = (menuCode) =>
{
    return menuDataGrid.Rows.Cast<DataGridViewRow>()
        .First(r => ((string)r.Cells[3].Value).Equals(menuCode));
};

var selected = menuListBox.SelectedItem.ToString();
pricetxtbox.Text = getRow(selected).Cells[5].Value.ToString();

totaltxtbox.Text = menuListBox.Items.Cast<object>()
    .Select(o => o.ToString())
    .Select(i => (int)getRow(i).Cells[5].Value)
    .Sum()
    .ToString();

答案 1 :(得分:0)

我认为你应该通过完全分离数据和显示来改变你的方法。 为此,您可以创建一个类,其中包含DataGrid的每一行的数据:

public class MyItem
{
    public string Caption { get; set; }
    public int Price { get; set; }
}

然后在你的代码隐藏中,你存储了这些项目的列表:

private List<MyItem> AllItems = new List<MyItem>();  

最后,将此集合设置为DataGrid的源:

menuDataGrid.DataSource = AllItems;

然后,您的所有数据都存储在您拥有的集合中,并且总结价格会更加简单:

using System.Linq;

private int ComputeSum()
{
    return (AllItems.Sum(item => item.Price));
}

下一步是使用Binding和BindingList,它允许DataGrid在&#34; AllItems&#34;中添加新项目时自动刷新:this well explained post