Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 901
Bernhard Avatar asked Dec 09 '25 12:12

Bernhard


2 Answers

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.");
    }
like image 148
monofonik Avatar answered Dec 11 '25 01:12

monofonik


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; }
}
like image 21
Tergiver Avatar answered Dec 11 '25 02:12

Tergiver