【发布时间】: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。