DrawListViewColumnHeaderEventArgs Class

Provides data for the ListView.DrawColumnHeader event.

Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in system.windows.forms.dll)

public ref class DrawListViewColumnHeaderEventArgs : public EventArgs
public class DrawListViewColumnHeaderEventArgs extends EventArgs
public class DrawListViewColumnHeaderEventArgs extends EventArgs
Not applicable.

The ListView.DrawColumnHeader event lets you customize (or owner-draw) the appearance of a ListView control in the details view.

The ListView.DrawColumnHeader event is raised by a ListView control when its ListView.OwnerDraw property is set to true and its View property is set to Details. The DrawListViewColumnHeaderEventArgs passed to the event handler contains information about the ColumnHeader to draw and also provides methods to help you draw the header.

Use the Header property to retrieve information about the column header to draw. Use the Graphics property to do the actual drawing within the area specified by the Bounds property. To draw standard ListView elements that do not need customization, use the DrawBackground and DrawText methods.

Use the DrawDefault property when you want the operating system to draw the subitem. This is useful when you want to customize only specific headers.

NoteNote:

To avoid issues with graphics flickering when owner drawing, override the ListView control and set the DoubleBuffered property to true. This feature is available only on Windows XP and the Windows Server 2003 family when your application calls the Application.EnableVisualStyles method.

The following code example demonstrates how to provide custom drawing for a ListView control. The ListView control in the example has a gradient background. Subitems with negative values have a red foreground and a black background.

A handler for the ListView.DrawItem event draws the background for entire items. A handler for the ListView.DrawSubItem event draws the text values and both the text and background for subitems that have negative values. A handler for the DrawColumnHeader event draws each column header.

A ContextMenu component provides a way to switch between the details view and the list view. In the list view, only the ListView.DrawItem event is fired. In this case, the text and background are both drawn in the ListView.DrawItem event handler.

#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Drawing::Drawing2D;
using namespace System::Globalization;
using namespace System::Windows::Forms;

public ref class ListViewOwnerDraw: public Form
{
private:
   ListView^ listView1;
   System::Windows::Forms::ContextMenu^ contextMenu1;

public:
   ListViewOwnerDraw()
   {
      listView1 = gcnew ListView;
      contextMenu1 = gcnew System::Windows::Forms::ContextMenu;

      // Initialize the ListView control.
      listView1->BackColor = Color::Black;
      listView1->ForeColor = Color::White;
      listView1->Dock = DockStyle::Fill;
      listView1->View = View::Details;
      listView1->FullRowSelect = true;

      // Add columns to the ListView control.
      listView1->Columns->Add( "Name", 72, HorizontalAlignment::Center );
      listView1->Columns->Add( "First", 72, HorizontalAlignment::Center );
      listView1->Columns->Add( "Second", 72, HorizontalAlignment::Center );
      listView1->Columns->Add( "Third", 72, HorizontalAlignment::Center );

      // Create items and add them to the ListView control.
      array<String^>^temp0 = {"One","20","30","-40"};
      ListViewItem^ listViewItem1 = gcnew ListViewItem( temp0,-1 );
      array<String^>^temp1 = {"Two","-250","145","37"};
      ListViewItem^ listViewItem2 = gcnew ListViewItem( temp1,-1 );
      array<String^>^temp2 = {"Three","200","800","-1,001"};
      ListViewItem^ listViewItem3 = gcnew ListViewItem( temp2,-1 );
      array<String^>^temp3 = {"Four","not available","-2","100"};
      ListViewItem^ listViewItem4 = gcnew ListViewItem( temp3,-1 );
      array<ListViewItem^>^temp4 = {listViewItem1,listViewItem2,listViewItem3,listViewItem4};
      listView1->Items->AddRange( temp4 );

      // Initialize the shortcut menu and 
      // assign it to the ListView control.
      contextMenu1->MenuItems->Add( "List", gcnew EventHandler( this, &ListViewOwnerDraw::menuItemList_Click ) );
      contextMenu1->MenuItems->Add( "Details", gcnew EventHandler( this, &ListViewOwnerDraw::menuItemDetails_Click ) );
      listView1->ContextMenu = contextMenu1;

      // Configure the ListView control for owner-draw and add 
      // handlers for the owner-draw events.
      listView1->OwnerDraw = true;
      listView1->DrawItem += gcnew DrawListViewItemEventHandler( this, &ListViewOwnerDraw::listView1_DrawItem );
      listView1->DrawSubItem += gcnew DrawListViewSubItemEventHandler( this, &ListViewOwnerDraw::listView1_DrawSubItem );
      listView1->DrawColumnHeader += gcnew DrawListViewColumnHeaderEventHandler( this, &ListViewOwnerDraw::listView1_DrawColumnHeader );

      //listView1.MouseMove += gcnew MouseEventHandler(&ListViewOwnerDraw::listView1_MouseMove);
      // Add a handler for the MouseUp event so an item can be 
      // selected by clicking anywhere along its width.
      listView1->MouseUp += gcnew MouseEventHandler( this, &ListViewOwnerDraw::listView1_MouseUp );

      // Initialize the form and add the ListView control to it.
      this->ClientSize = System::Drawing::Size( 292, 79 );
      this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedSingle;
      this->MaximizeBox = false;
      this->Text = "ListView OwnerDraw Example";
      this->Controls->Add( listView1 );
   }

   // Clean up any resources being used.        
public:
   ~ListViewOwnerDraw()
   {
      if ( contextMenu1 != nullptr )
      {
         delete contextMenu1;
      }
   }

private:

   // Sets the ListView control to the List view.
   void menuItemList_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      listView1->View = View::List;
   }

   // Sets the ListView control to the Details view.
   void menuItemDetails_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      listView1->View = View::Details;
   }

   // Selects and focuses an item when it is clicked anywhere along 
   // its width. The click must normally be on the parent item text.
   void listView1_MouseUp( Object^ /*sender*/, MouseEventArgs^ e )
   {
      ListViewItem^ clickedItem = listView1->GetItemAt( 5, e->Y );
      if ( clickedItem != nullptr )
      {
         clickedItem->Selected = true;
         clickedItem->Focused = true;
      }
   }

   // Draws the backgrounds for entire ListView items.
private:
   void listView1_DrawItem( Object^ /*sender*/, DrawListViewItemEventArgs^ e )
   {
      if ( (e->State & ListViewItemStates::Selected) != (ListViewItemStates)0 )
      {
         // Draw the background for a selected item.
         e->Graphics->FillRectangle( Brushes::Maroon, e->Bounds );
         e->DrawFocusRectangle();
      }
      else
      {
         // Draw the background for an unselected item.
         LinearGradientBrush^ myBrush = gcnew LinearGradientBrush( e->Bounds,Color::Orange,Color::Maroon,LinearGradientMode::Horizontal );
         try
         {
            e->Graphics->FillRectangle( myBrush, e->Bounds );
         }
         finally
         {
            if ( myBrush )
               delete (IDisposable^)myBrush;
         }
      }

      if ( listView1->View != View::Details )
      {
         e->DrawText();
      }
   }

   // Draws subitem text and applies content-based formatting.
private:
   void listView1_DrawSubItem( Object^ /*sender*/, DrawListViewSubItemEventArgs^ e )
   {
      TextFormatFlags flags = TextFormatFlags::Left;
      StringFormat^ sf = gcnew StringFormat;
      try
      {
         // 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;
               flags = TextFormatFlags::HorizontalCenter;
               break;

            case HorizontalAlignment::Right:
               sf->Alignment = StringAlignment::Far;
               flags = TextFormatFlags::Right;
               break;
         }

         // Draw the text and background for a subitem with a 
         // negative value. 
         double subItemValue;
         if ( e->ColumnIndex > 0 && Double::TryParse( e->SubItem->Text, NumberStyles::Currency, NumberFormatInfo::CurrentInfo, subItemValue ) && subItemValue < 0 )
         {
            // Unless the item is selected, draw the standard 
            // background to make it stand out from the gradient.
            if ( (e->ItemState & ListViewItemStates::Selected) == (ListViewItemStates)0 )
            {
               e->DrawBackground();
            }

            // Draw the subitem text in red to highlight it. 
            e->Graphics->DrawString( e->SubItem->Text, listView1->Font, Brushes::Red, e->Bounds, sf );
            return;
         }

         // Draw normal text for a subitem with a nonnegative 
         // or nonnumerical value.
         e->DrawText( flags );
      }
      finally
      {
         if ( sf )
            delete (IDisposable^)sf;
      }
   }

   // Draws column headers.
private:
   void listView1_DrawColumnHeader( Object^ /*sender*/, DrawListViewColumnHeaderEventArgs^ e )
   {
      StringFormat^ sf = gcnew StringFormat;
      try
      {
         // 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.
         System::Drawing::Font^ headerFont = gcnew System::Drawing::Font( "Helvetica",10,FontStyle::Bold );
         try
         {
            e->Graphics->DrawString( e->Header->Text, headerFont, Brushes::Black, e->Bounds, sf );
         }
         finally
         {
            if ( headerFont )
               delete (IDisposable^)headerFont;
         }
      }
      finally
      {
         if ( sf )
            delete (IDisposable^)sf;
      }

      return;
   }

   // Forces the row the mouse is on to repaint itself. 
   void listView1_MouseMove( Object^ /*sender*/, MouseEventArgs^ e )
   {
      ListViewItem^ item = listView1->GetItemAt( e->X, e->Y );
      if ( item != nullptr )
      {
         listView1->Invalidate( item->Bounds );
      }
   }
};

[STAThread]
int main()
{
   Application::Run( gcnew ListViewOwnerDraw );
}

import System.*;
import System.Drawing.*;
import System.Drawing.Drawing2D.*;
import System.Globalization.*;
import System.Windows.Forms.*;

public class ListViewOwnerDraw extends Form
{
    private ListView myListView;
    private ContextMenu myContextMenu;

    public ListViewOwnerDraw()
    {
        // Create and initialize the ListView control.
        myListView = new ListView();
        myListView.set_BackColor(Color.get_Black());
        myListView.set_ForeColor(Color.get_White());
        myListView.set_Dock(DockStyle.Fill);
        myListView.set_View(View.Details);

        // Add columns to the ListView control.
        myListView.get_Columns().Add("Name", 72, HorizontalAlignment.Center);
        myListView.get_Columns().Add("First", 72, HorizontalAlignment.Center);
        myListView.get_Columns().Add("Second", 72, HorizontalAlignment.Center);
        myListView.get_Columns().Add("Third", 72, HorizontalAlignment.Center);

        // Create items and add them to the ListView control.
        ListViewItem listViewItem1 = new ListViewItem(new String[] 
            { "One", "20", "30", "-40" }, -1);
        ListViewItem listViewItem2 = new ListViewItem(new String[] 
            { "Two", "-250", "145", "37" }, -1);
        ListViewItem listViewItem3 = new ListViewItem(new String[] 
            { "Three", "200", "800", "-1,001" }, -1);
        ListViewItem listViewItem4 = new ListViewItem(new String[] 
            { "Four", "not available", "-2", "100" }, -1);
        myListView.get_Items().AddRange(new ListViewItem[] { listViewItem1, 
            listViewItem2, listViewItem3, listViewItem4 });

        // Create a shortcut menu for changing views and 
        // assign it to the ListView control.
        myContextMenu = new ContextMenu();
        myContextMenu.get_MenuItems().Add("List", 
            new EventHandler(menuItemList_Click));
        myContextMenu.get_MenuItems().Add("Details", 
            new EventHandler(menuItemDetails_Click));
        myListView.set_ContextMenu(myContextMenu);

        // Configure the ListView control for owner-draw and add 
        // handlers for the owner-draw events.
        myListView.set_OwnerDraw(true);
        myListView.add_DrawItem(new DrawListViewItemEventHandler(
            myListView_DrawItem));
        myListView.add_DrawSubItem(new DrawListViewSubItemEventHandler(
            myListView_DrawSubItem));

        // Add a handler for the MouseUp event so an item can be 
        // selected by clicking anywhere along its width.
        myListView.add_MouseUp(new MouseEventHandler(myListView_MouseUp));

        // Initialize the form and add the ListView control to it.
        this.set_ClientSize(new Size(292, 79));
        this.set_FormBorderStyle(get_FormBorderStyle().FixedSingle);
        this.set_MaximizeBox(false);
        this.set_Text("ListView OwnerDraw Example");
        this.get_Controls().Add(myListView);
    } //ListViewOwnerDraw

    // Clean up any resources being used.        
    protected void Dispose(boolean disposing)
    {
        if (disposing) {
            myContextMenu.Dispose();
        }
        super.Dispose(disposing);
    } //Dispose

    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        Application.Run(new ListViewOwnerDraw());
    } //main

    // Sets the ListView control to the List view.
    private void menuItemList_Click(Object sender, EventArgs e)
    {
        myListView.set_View(View.List);
    } //menuItemList_Click

    // Sets the ListView control to the Details view.
    private void menuItemDetails_Click(Object sender, EventArgs e)
    {
        myListView.set_View(View.Details);
    } //menuItemDetails_Click

    // Selects and focuses an item when it is clicked anywhere along 
    // its width. The click must normally be on the parent item text.
    private void myListView_MouseUp(Object sender, MouseEventArgs e)
    {
        ListViewItem clickedItem = myListView.GetItemAt(5, e.get_Y());
        if (clickedItem != null) {
            clickedItem.set_Selected(true);
            clickedItem.set_Focused(true);
        }
    } //myListView_MouseUp

    // Draws the backgrounds for the column header row and for entire
    // ListView items.
    private void myListView_DrawItem(Object sender, DrawListViewItemEventArgs e)
    {
        // Draw the background for the column header row.
        if (e.get_ItemIndex() == -1) {
            e.get_Item().set_BackColor(Color.get_Black());
            e.DrawBackground();
        }
        // Draw the background for a selected item.
        else {
            if (Convert.ToInt32((e.get_State() & ListViewItemStates.Selected))
                != 0) {
                e.get_Graphics().FillRectangle(Brushes.get_Maroon(),
                    e.get_Bounds());
                e.DrawFocusRectangle();
            }
            // Draw the background for an unselected item.
            else {
                LinearGradientBrush myBrush = new LinearGradientBrush(
                    e.get_Bounds(), Color.get_Orange(), Color.get_Maroon(),
                    LinearGradientMode.Horizontal);
                try {
                    e.get_Graphics().FillRectangle(myBrush, e.get_Bounds());
                }
                finally {
                    myBrush.Dispose();
                }    
            }
        }
        // Draw the item text for views other than the Details view.
        if (!(((ListView)sender).get_View().Equals(View.Details))) {
            e.DrawText();
        }
    } //myListView_DrawItem

    // Draws subitem text and applies content-based formatting.
    private void myListView_DrawSubItem(Object sender,
        DrawListViewSubItemEventArgs e)
    {
        TextFormatFlags flags = TextFormatFlags.Left;
        StringFormat sf = new StringFormat();
        try {
            // Store the column text alignment, letting it default
            // to Left if it has not been set to Center or Right.
            if (e.get_Header().get_TextAlign().
                Equals(HorizontalAlignment.Center)) {

                sf.set_Alignment(StringAlignment.Center);
                flags = TextFormatFlags.HorizontalCenter;
            }
            else {
                if (e.get_Header().get_TextAlign().
                    Equals(HorizontalAlignment.Right)) {

                    sf.set_Alignment(StringAlignment.Far);
                    flags = TextFormatFlags.Right;
                }
            }
            // Draw the text for a column header.
            if (e.get_ItemIndex() == -1) {
                Font myFont = new Font("Helvetica", 12, FontStyle.Bold);
                try {
                    e.get_Graphics().DrawString(e.get_Item().get_Text(), 
                        myFont, Brushes.get_White(), 
                        new PointF((float)e.get_Bounds().get_X(), 
                        (float)e.get_Bounds().get_Y()), sf);
                }
                finally {
                    myFont.Dispose();
                }
                return;
            }

            // Draw the text and background for a subitem with a 
            // negative value. 
            double subItemValue = 0;
            if (e.get_ColumnIndex() > 0 && System.Double.TryParse(
                e.get_Item().get_SubItems().get_Item(e.get_ColumnIndex()).
                get_Text(), NumberStyles.Currency, 
                NumberFormatInfo.get_CurrentInfo(), subItemValue) 
                && subItemValue < 0) {

                // Unless the item is selected, draw the standard 
                // background to make it stand out from the gradient.
                if (Convert.ToInt32(e.get_ItemState() 
                    & ListViewItemStates.Selected) == 0) {
                    e.DrawBackground();
                }
                // Draw the subitem text in red to highlight it. 
                e.get_Graphics().DrawString(e.get_Item().get_SubItems().
                    get_Item(e.get_ColumnIndex()).get_Text(), 
                    ((ListView)sender).get_Font(), Brushes.get_Red(), 
                    RectangleF.op_Implicit(e.get_Bounds()), sf);

                return;
            }
            // Draw normal text for a subitem with a nonnegative 
            // or nonnumerical value.
            e.DrawText(flags);
        }
        finally {
            sf.Dispose();
        }
    } //myListView_DrawSubItem
} //ListViewOwnerDraw 

System.Object
   System.EventArgs
    System.Windows.Forms.DrawListViewColumnHeaderEventArgs

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0

Community Additions

ADD
Show: