4

I have the following method to set background color and Font for the list view's column headers but it is not working. Anybody can help me?

private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
    using (StringFormat sf = new StringFormat())
    {
        // Store the column text alignment, letting it default
        // to Left if it has not been set to Center or Right.
        switch (e.Header.TextAlign)
        {
            case HorizontalAlignment.Center:
                sf.Alignment = StringAlignment.Center;
                break;
            case HorizontalAlignment.Right:
                sf.Alignment = StringAlignment.Far;
                break;
        }

        // Draw the standard header background.
        e.DrawBackground();

        // Draw the header text.
        using (Font headerFont = new Font("Helvetica", 25, FontStyle.Bold)) //Font size!!!!
        {
            e.Graphics.DrawString(e.Header.Text, headerFont, Brushes.Black, e.Bounds, sf);
        }
    }
    return;
}

It doesn't matter I use this method or not. It remains same. Nothing changes. Is it because of properties of the list view?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
a-f-a
  • 147
  • 1
  • 3
  • 9

1 Answers1

4

Your code looks ok. If it doesn't do anything you have forgotten to set the OwnerDraw property to true.

This also means that you need to add code for the other two draw events. The default actions will do:

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


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

Don't forget to hook up the events ;-)

Community
  • 1
  • 1
TaW
  • 53,122
  • 8
  • 69
  • 111
  • @a-f-a When an answer helped you solve the problem and you accepted it, you can also kindly consider [voting it up](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work), while it is not compulsory, but it is reasonable :) – Reza Aghaei Nov 23 '15 at 08:39
  • Yeah. I will learn this kind of things in time. I am new here :) – a-f-a Nov 24 '15 at 17:18