How do we change the header BackColor and selected color in ListView using c#?

How do we change the header BackColor and selected color in ListView using c#?

Yes, we can make it possible to change the header backcolor and style for ListView control. And also we can change the some styles in ListView control in the code behind. Here is the way to explain how it is possible.

There is property named “OwnerDraw” is used to do the style changing process by our code behind. Just we need to set that property as “true”.

I have a ListView control with the name of “lstView” in my sample form, and the code has been written as follows,

this.lstView.BackColor = System.Drawing.SystemColors.ControlText;
this.lstView.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lstView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2,
this.columnHeader3});
this.lstView.ForeColor = System.Drawing.SystemColors.ControlLightLight;
this.lstView.FullRowSelect = true;
this.lstView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.lstView.Location = new System.Drawing.Point(2, 1);
this.lstView.MultiSelect = false;
this.lstView.Name = "lstView";
this.lstView.OwnerDraw = true;
this.lstView.View = System.Windows.Forms.View.Details;

private void lstView_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
System.Drawing.Drawing2D.LinearGradientBrush GradientBrush = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, Color.Blue, Color.LightBlue, 270);

e.Graphics.FillRectangle(GradientBrush, e.Bounds);

e.Graphics.DrawRectangle(new Pen(new SolidBrush(Color.White), 2), e.Bounds.X + 1, e.Bounds.Y + 1, e.Bounds.Width - 2, e.Bounds.Height - 2);

e.Graphics.DrawString(e.Header.Text, new Font("Arial", 12), new SolidBrush(Color.Yellow), e.Bounds);
}

private void lstView_DrawItem(object sender, DrawListViewItemEventArgs e)
{
if (e.Item.Selected)
{
e.Graphics.FillRectangle(new SolidBrush(Color.DarkBlue), e.Bounds);
}
e.Graphics.DrawString(e.Item.Text, new Font("Arial", 10), new SolidBrush(Color.White), e.Bounds);
}


private void lstView_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
e.Graphics.DrawString(e.Item.Text, new Font("Arial", 10), new SolidBrush(Color.White), e.Bounds);
}


That's it...

...S.VinothkumaR.

1 comment:

Hugo Barros said...

Thanks bro, very useful your code.