Bernhard
Bernhard

Reputation: 1485

C# ListView check if ListViewItem is checked

I am creating a listview with a collections of ListViewItems, all with checkboxes. I want to check wich Item is checked. I know how to launch the ItemChecked event but the event is launched every time an ListViewItem is added to the ListView. How can I prevent this?


To help you understand what I want to do, here is a little info about the application.

I am building a application for Red Cross dispatchers. It will help them keep track of the units in the field. The application is used to, among other things, log the transmissions. When during a transmission a priorety transmission comes in, the current unit will be set on hold. This will be done by checking the checkbox belonging to the units ListViewItem.

By checking the checkbox, the object (with the type Unit) will set the property objUnit.onHold to true. When the checkbox is unchecked the property will be set to false again. Every 3 minutes the application will loop through all units to see if anyone is still on hold. If so, a messagebox will popup reminding the dispatcher of the unit on hold.

So you see, I have to be sure that the dispatcher really checked or unchecked the ListViewItem.

I hope someone can point me in the right direction.

Upvotes: 3

Views: 12896

Answers (3)

monofonik
monofonik

Reputation: 2845

If you use the ItemCheck event instead of ItemChecked, the event will not be triggered when a new item is added to the list.

    //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.");
    }

Upvotes: 2

Andrew
Andrew

Reputation: 2665

There is a CheckedItems property on the listview you could use ListView.CheckedItems Property (System.Windows.Forms)

Upvotes: 0

Tergiver
Tergiver

Reputation: 14507

You can set a flag indicating that you are inserting an item and ignore the event if the flag is checked.

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; }
}

Upvotes: 1

Related Questions