【问题标题】:Display the sum of all items inside listbox显示列表框中所有项目的总和
【发布时间】:2017-11-20 15:35:10
【问题描述】:

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

我要做的是显示所有商品价格的总和并显示在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;
        } 
    }

将不胜感激任何帮助!谢谢!

【问题讨论】:

  • row 对象仅存在于第一个 foreach 循环中,因此将第二个 foreach 移动到第一个循环中。你也不需要(或想要)break
  • 我需要澄清一下。您是否在 DataGridView 中搜索 ListBox 中的选定项目,然后显示该价格?如果是这样,对于 ListBox 中的一项,DataGridView 中是否有多个匹配项?总价是否应该是所有价格的总和,而不管 ListBox 中的选定项目如何?
  • @BlakeThingstad ListBox 中的项目来自 DataGridView。生病将一个项目拖到列表框,它将添加项目的MenuCode。如果我在 ListBox 中选择一个项目,则 `MenuPrice 将在第一个 TextBox 上播放。现在我想要发生的是,如果我在 ListBox 中有 2 个项目,例如价格是 100 和 50,则两者的总和将相加并出现在第二个 TextBox 中。我将编辑我的帖子并包含我获取项目的 DataGridView。

标签: c# winforms listbox


【解决方案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();

【讨论】:

  • 这绝对是我想要的。它成功了……谢谢!标记为答案。
【解决方案2】:

我认为您应该改变方法,将数据和显示完全分开。 为此,您可以创建一个包含 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 在“AllItems”中添加新项目时自动刷新:请参阅 this well explained post

【讨论】:

  • 你好@Elo。我会考虑这个并会尝试。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
  • 2016-03-22
相关资源
最近更新 更多