从C#

时间:2019-01-07 17:11:13

标签: c# .net

我当前的代码非常适合将项目添加到ListView中,并且删除功能也非常有效!然而!有时,当我从列表视图中删除一个项目并尝试添加另一个项目时,它不会为其添加适当的子项目。

我尝试调试代码并尝试跟踪变量,但无济于事。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ListViewExampleA
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int a = 0;
        private void button1_Click(object sender, EventArgs e)
        {
            // Insert name into column 1.
            listView1.Items.Add(textBox1.Text);

            // Insert country into column 2.
            listView1.Items[a].SubItems.Add(textBox2.Text);

            // Insert age into column 3.
            listView1.Items[a].SubItems.Add(textBox3.Text);

            // Increment i.
            a++;

            // Empty tbox1, 2, 3
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
        }

        // The following event runs every time, the second button which is (Remove From The List) is clicked
        private void button2_Click(object sender, EventArgs e)
        {
            // So we can work with them easier.
            string name = textBox1.Text;
            string country = textBox2.Text;
            string age = textBox3.Text;

            // If only name is written and the rest are empty
            if (name != "" && country == "" && age == "")
            {                   
                for (int i = 0; i < listView1.Items.Count; i++)
                {
                    listView1.Items.Remove(listView1.FindItemWithText(name));
                    a--;
                }

            }

            // If only
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您需要从头开始删除,否则将跳过项目

for (int i = listView1.Items.Count - 1; i >= 0; i--)
{
   if(listView1.Items[i].Text == Name) listView1.Items[i].Remove();
}