Search code examples
c#winformslistviewlistviewitem

Remove space between left ListView border and column items


enter image description here

I colored a few items of the first ListView column by

foreach (ListViewItem lvi in listView.Items)
{
    lvi.UseItemStyleForSubItems = false;

    lvi.SubItems[0].BackColor = Color.DarkMagenta;
}

and try to get rid of the outlined gap between the left ListView border and the column items.

Setting listView.Padding has no effect, ColumnHeader class has neither a BackColor property nor a Margin property which could be set below zero.


Solution

  • Owner-Drawing will let you paint the whole Item background as you like.

    listView1.OwnerDraw = true;
    

    Here is a simple, minimal example:

    private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
    {
        using (Brush brush = new SolidBrush(
                (e.State.HasFlag(ListViewItemStates.Focused)) ? 
                SystemColors.Highlight : e.Item.BackColor))
            e.Graphics.FillRectangle(brush, e.Bounds);
        e.DrawText();
    }
    

    Note that once you owner draw the item you will aslo need to owner-draw the sub-items and the headers, even if you just use the defaults:

    private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
    {
        e.DrawDefault = true;
    }
    
    private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
    {
        e.DrawDefault = true;
    }