Search code examples
c#winformslistviewempty-list

Display empty text when there are no items in ListView Windows forms


I'm trying to display an empty text message inside a listview when I have no items inside it (that's when the form is initialized).

I've tried searching different method out of which one is using the `OnPaint() event , but that didn't work out well...

Can someone help me out ? ` Edit: this is one of the methods I've tried:

  protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == 20)
            {
                if (this.Items.Count == 0)
                {
                    _b = true;
                    Graphics g = this.CreateGraphics();
                    int w = (this.Width - g.MeasureString(_msg,
                      this.Font).ToSize().Width) / 2;
                    g.DrawString(_msg, this.Font,
                      SystemBrushes.ControlText, w, 30);
                }
                else
                {
                    if (_b)
                    {
                        this.Invalidate();
                        _b = false;
                    }
                }
            }

            if (m.Msg == 4127) this.Invalidate();
        }

Solution

  • You can handle WM_PAINT(0xF) message and check if there is no item in Items collection, draw a string in center of your ListView. For example:

    using System.Windows.Forms;
    using System.ComponentModel;
    using System.Drawing;
    
    public class MyListView : ListView
    {
        public MyListView()
        {
            EmptyText = "No data available.";
        }
        [DefaultValue("No data available.")]
        public string EmptyText { get; set; }
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == 0xF)
            {
                if (this.Items.Count == 0)
                    using (var g = Graphics.FromHwnd(this.Handle))
                        TextRenderer.DrawText(g, EmptyText, Font, ClientRectangle, ForeColor);
            }
        }
    }