C# ListView如何检查ListViewItem是否被选中

3
我正在创建一个ListView,其中包含多个带有复选框的ListViewItems。我想要检查哪个Item被选中了。我知道如何启动ItemChecked事件,但是每次向ListView添加ListViewItem时都会触发该事件。我该如何防止这种情况发生?
为了帮助你理解我的需求,以下是一些关于应用程序的信息。
我正在为红十字会调度员构建一个应用程序。它将帮助他们跟踪外勤部队。该应用程序用于记录传输等内容。当在传输过程中发生优先传输时,当前部队将被设置为暂停。这将通过检查与部队的ListViewItem相关联的复选框来完成。
通过勾选复选框,类型为Unit的对象将设置属性objUnit.onHold为true。当取消选中复选框时,该属性将再次设置为false。每3分钟,应用程序将循环遍历所有单位,以查看是否仍有任何单位处于暂停状态。如果是,则会弹出消息框提醒调度员该单位正在暂停。
因此,我必须确保调度员确实已经选中或取消选中了ListViewItem。
我希望有人能指点我正确的方向。

如果您没有看到有用的答案,可以添加评论以提出跟进问题。如果答案有用,您可以通过投票来提供反馈。 - Andrew
3个回答

2
如果您使用ItemCheck事件而不是ItemChecked事件,当向列表中添加新项时,该事件不会被触发。
    //Counter to differentiate list items
    private int counter = 1;

    private void button1_Click(object sender, EventArgs e)
    {
        //Add a new item to the list
        listView1.Items.Add(new ListViewItem("List item " + counter++.ToString()));
    }

    private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        //Get the item that was checked / unchecked
        ListViewItem l = listView1.Items[e.Index];

        //Display message
        if (e.NewValue == CheckState.Checked)
            MessageBox.Show(l.ToString() + " was just checked.");

        else if (e.NewValue == CheckState.Unchecked)
            MessageBox.Show(l.ToString() + " was just unchecked.");
    }

1

您可以设置一个标志,表示您正在插入一个项目,并在检查该标志时忽略事件。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

class Form1 : Form
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    ListView listView;
    List<Unit> units;
    bool insertingItem = false;

    public Form1()
    {
        Controls.Add(listView = new ListView
        {
            Dock = DockStyle.Fill,
            View = View.Details,
            CheckBoxes = true,
            Columns = { "Name" },
        });

        Controls.Add(new Button { Text = "Add", Dock = DockStyle.Top });
        Controls[1].Click += (s, e) => AddNewItem();

        listView.ItemChecked += (s, e) =>
            {
                Unit unit = e.Item.Tag as Unit;
                Debug.Write(String.Format("Item '{0}' checked = {1}", unit.Name, unit.OnHold));
                if (insertingItem)
                {
                    Debug.Write(" [Ignored]");
                }
                else
                {
                    Debug.Write(String.Format(", setting checked = {0}", e.Item.Checked));
                    unit.OnHold = e.Item.Checked;
                }
                Debug.WriteLine("");
            };

        units = new List<Unit> { };
    }

    Random Rand = new Random();
    int NameIndex = 0;
    readonly string[] Names = { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten" };
    void AddNewItem()
    {
        if (NameIndex < Names.Length)
        {
            Unit newUnit = new Unit { Name = Names[NameIndex++], OnHold = Rand.NextDouble() < 0.6 };
            units.Add(newUnit);
            insertingItem = true;
            try
            {
                listView.Items.Add(new ListViewItem { Text = newUnit.Name, Checked = newUnit.OnHold, Tag = newUnit });
            }
            finally
            {
                insertingItem = false;
            }
        }
    }
}

class Unit
{
    public string Name { get; set; }
    public bool OnHold { get; set; }
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接