【问题标题】:Edit listview item based on click_event c#基于click_event c#编辑listview项目
【发布时间】:2020-05-23 10:35:05
【问题描述】:

我创建了一个列表视图

        ListView ListView1 = new ListView();
        ListView1.Location = new System.Drawing.Point(12, 12);
        ListView1.Name = "ListView1";
        ListView1.Size = new System.Drawing.Size(280, 300);
        ListView1.BackColor = System.Drawing.Color.White;
        ListView1.ForeColor = System.Drawing.Color.Black;
        ListView1.View = View.Details;
        ListView1.GridLines = true;
        ListView1.FullRowSelect = true;
        ListView1.Columns.Add("ProductName", 100);
        ListView1.Columns.Add("Quantity", 100);
        ListView1.Columns.Add("Price", 100);

我使用以下代码向其中添加项目:

b.Click += (s, e) => {
                    string[] arr = new string[4];
                    ListViewItem itm;
                    arr[0] = b.Text;
                    arr[1] = x.ToString();
                    arr[2] = price;
                    itm = new ListViewItem(arr);
                    ListView1.Items.Add(itm);
                    x++;
                    };

b 是一个自动生成的按钮,我想要实现的很简单,每次单击按钮 b 时,变量 x 的值都会增加 1,x 表示数量。 我想要的是: 每当我单击按钮 b 时,具有 Column["Productname"]=b.Text 的当前项目的数量都会改变 我得到了什么: 数量发生了变化,但项目被重新插入,所以我想先检查项目是否存在(基于 Column[“Productname”]),如果确实存在,则数量增加 1。

image_to_help_understand

更多细节:对不起,如果这太长了,但我只是有一些自动生成的按钮,每个按钮代表一个产品,当用户点击产品时,它会被添加到列表中(稍后购买) 并且如果客户点击同一个产品 n 次,则 Quantity 应该变为 Quantity=n 而无需再次添加该项目。谢谢大家,很抱歉发了这么长的帖子。

【问题讨论】:

  • 谢谢,但 FinditemwithText 不会替换值,这就是我需要的
  • 我应该更好地阅读您的问题。我以为您可以使用 FindItemWithText 找到现有项目,如果是这样,请增加数量 using edit in place
  • 非常感谢,我找到了解决方案!当我不应该使用 While 循环时,我让事情变得更难了......但幸运的是我想通了:

标签: c# winforms listview search replace


【解决方案1】:

将值插入 UI 并不是一个好的设计。我以前的 cmets 有这些变化。使用 BindingList、公共类 Product : INotifyPropertyChanged,并将 ListView 替换为 DataGridView。这只是让生活变得更轻松,代码也很简单。自己创建 ListBoxItems 不是一种好的做事方式。 顺便说一句:要查找产品,您只需对 ProductCollection 使用 LINQ 查询。无需搜索 UI。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    • 2021-01-20
    相关资源
    最近更新 更多