6

The common way to NOT display a ListViewItem is to remove it.
I my current project, this makes things too complicated compared to the possibility of just hiding the item.

Is there any way to hide a ListViewItem instead of removing it?

What I have tried so far:

  1. Using OwnerDraw=true, the DrawItem event doesn't provide anything useful:
    Bounds is read-only and changing properties of Item is useless.

  2. Inherit ListView and override WndProc was my next attempt,
    but I was not able to find any of the LVM_??? messages that helps.
    LVM_SETITEMPOSITION is only used when Viewis icon or small icon.

joe
  • 8,344
  • 9
  • 54
  • 80

1 Answers1

2

You could maintain an internal list that stores an Item that subclasses ListViewItem and has a Visible field. Here's the basic idea:

public class ListView2 : ListView {

    private List<Item2> list = new List<Item2>();

    public class Item2 : ListViewItem {
        public bool Visible = true;
        public Object Value = null;

        public override string ToString() {
            return (Value == null ? String.Empty : Value.ToString());
        }
    }

    public Item2 this[int i] {
        get {
            return list[i];
        }
    }

    public int Count {
        get {
            return list.Count;
        }
    }

    public void Add(Object o) {
        Item2 item = new Item2 { Value = o, Text = (o == null ? string.Empty : o.ToString()) };
        Items.Add(item);
        list.Add(item);
    }

    public void RefreshVisibleItems() {
        var top = (Item2) this.TopItem;
        Items.Clear();
        int k = 0;
        foreach (var o in list) {
            if (o == top)
                break;
            if (o.Visible)
                k++;
        }
        Items.AddRange(list.FindAll(i => i.Visible).ToArray());
        if (k < Items.Count)
            this.TopItem = Items[k];
    }
}


    var lv = new ListView2();
    lv.View = View.Details;
    lv.Columns.Add("Column1", 100, HorizontalAlignment.Center);

    Button btn = new Button { Text = "Hide" , Dock = DockStyle.Bottom };
    lv.Dock = DockStyle.Fill;
    for (char c = 'A'; c <= 'Z'; c++)
        lv.Add(c);

    var f1 = new Form1();
    f1.Controls.Add(lv);
    f1.Controls.Add(btn);

    btn.Click += delegate {
        if (lv.Items.Count == 0) {
            for (int i = 0; i < lv.Count; i++)
                lv[i].Visible = true;
        }
        else {
            lv[lv.Items.Count - 1].Visible = false;
        }
        lv.RefreshVisibleItems();
    };


    Application.Run(f1);
Loathing
  • 5,109
  • 3
  • 24
  • 35