C# 列表视图的一行正在更新,但也插入了重复的行
大家好,我正在尝试更新正在订购的产品的数量。如果产品已存在于用户的购物篮中,而不是插入新行,则应更新包含现有项目的行中的数量。它正在更新,但还会插入一个新行,其中包含应添加到原始行的数量,如下所示: 我猜我的代码在逻辑上有问题,但我无法发现C# 列表视图的一行正在更新,但也插入了重复的行,c#,windows,forms,list,view,C#,Windows,Forms,List,View,大家好,我正在尝试更新正在订购的产品的数量。如果产品已存在于用户的购物篮中,而不是插入新行,则应更新包含现有项目的行中的数量。它正在更新,但还会插入一个新行,其中包含应添加到原始行的数量,如下所示: 我猜我的代码在逻辑上有问题,但我无法发现 private void btn_add_Click(object sender, EventArgs e) { try { ListViewItem item = new ListView
private void btn_add_Click(object sender, EventArgs e)
{
try
{
ListViewItem item = new ListViewItem(list_Select_Product.SelectedItems[0].Text);
item.SubItems.Add(list_Select_Product.SelectedItems[0].SubItems[1].Text);
item.SubItems.Add(txt_quantity.Text);
bool ok = true;
if (!validNumbers(txt_quantity))
ok = false;
if (!validLength(txt_quantity, 1, 2))
ok = false;
if (ok == true)
{
foreach (ListViewItem lvi in list_view_orderitems.Items)
{
if(lvi.SubItems[0].Text == list_Select_Product.SelectedItems[0].Text)
{
int UpdateQunat = Convert.ToInt32(lvi.SubItems[2].Text);
int AddMe = Convert.ToInt32(txt_quantity.Text);
UpdateQunat = UpdateQunat + AddMe;
lvi.SubItems[2].Text = Convert.ToString(UpdateQunat);
list_view_orderitems.Items.Add(item);
}
else if (lvi.SubItems[0].Text != list_Select_Product.SelectedItems[0].Text)
{
list_view_orderitems.Items.Add(item);
}
}
if(list_view_orderitems.Items.Count == 0)
{
list_view_orderitems.Items.Add(item);
}
}
}
catch
{
MessageBox.Show("A product must be selected");
}
}
在foreach循环中看得更近一点。实际上你也把它加在那里了。(因此您应该删除该选项)
我认为这是
如果你需要去掉这个项目。添加(我标记了它:
if(lvi.SubItems[0].Text == list_Select_Product.SelectedItems[0].Text)
{
int UpdateQunat = Convert.ToInt32(lvi.SubItems[2].Text);
int AddMe = Convert.ToInt32(txt_quantity.Text);
UpdateQunat = UpdateQunat + AddMe;
lvi.SubItems[2].Text = Convert.ToString(UpdateQunat);
// list_view_orderitems.Items.Add(item);
}
干杯,真不敢相信我没发现。谢谢!我们中最棒的人都会这样!
if(lvi.SubItems[0].Text == list_Select_Product.SelectedItems[0].Text)
{
int UpdateQunat = Convert.ToInt32(lvi.SubItems[2].Text);
int AddMe = Convert.ToInt32(txt_quantity.Text);
UpdateQunat = UpdateQunat + AddMe;
lvi.SubItems[2].Text = Convert.ToString(UpdateQunat);
// list_view_orderitems.Items.Add(item);
}