Paul Scharnofske Paul Scharnofske - 1 year ago 173
C# Question

ListView - Align vertical grid lines with Headers dividers - Make last Column fill the space

I am trying to write a Windows Forms MusicPlayer application in C#.

The application should show a list and have some play / stop buttons.

I just started half an hour ago, but my design is almost finished. Now I got 3 things to fix. A bug and 2 good looking things:

  1. on the picture you can see the bug I've found. You might say that's nothing, but its a eye catcher. How can I fix this?


  2. how can I align center the headline of a column, without centering the content?

  3. how can I make the last column filling out the rest of the listView?

Answer Source
  • You can set the TextAlign of all but the 1st Column's Header; it is always left aligned. To change that you need to owner draw it.

  • There is no automatic filling option so you need to write a setColumnwidth function, that loops over all but the last columns and sums their Widths; then it subtract the sum from the ListView's Clientsize.Width and set the last column's Width.

  • The display bug in the gridlines is new to me; so far I don't know how to fix it; maybe owner-drawing will help there as well..?


Here is some code:

void setLastColumnTofill(ListView lv)
     int sum = 0;
     int count  = lv.Columns.Count;
     for (int i = 0; i < count   - 1; i++) sum += lv.Columns[i].Width;
     lv.Columns[count   - 1].Width = lv.ClientSize.Width - sum;

After setting OwnerDraw = true you could code the three (all are needed!) Draw event :

private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
    e.Graphics.FillRectangle(SystemBrushes.Menu, e.Bounds);
        new Rectangle(e.Bounds.X , 0, e.Bounds.Width , e.Bounds.Height) );

    string text = listView1.Columns[e.ColumnIndex].Text;
    TextFormatFlags cFlag = TextFormatFlags.HorizontalCenter 
                          | TextFormatFlags.VerticalCenter;
    TextRenderer.DrawText(e.Graphics, text, listView1.Font, e.Bounds, Color.Black, cFlag);

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
    e.DrawDefault = true;

private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
    e.DrawDefault = true;

You may want to play a little with the colors or the widths..

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download