Export (0) Print
Expand All
Expand Minimize

DataGridView.ColumnHeaderMouseClick Event

Note: This event is new in the .NET Framework version 2.0.

Occurs when the user clicks a column header.

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

public event DataGridViewCellMouseEventHandler ColumnHeaderMouseClick
/** @event */
public void add_ColumnHeaderMouseClick (DataGridViewCellMouseEventHandler value)

/** @event */
public void remove_ColumnHeaderMouseClick (DataGridViewCellMouseEventHandler value)

JScript supports the use of events, but not the declaration of new ones.

For more information about handling events, see Consuming Events.

The following code example demonstrates how to use this event to perform a programmatic sort that emulates the default behavior of clicking a DataGridViewColumnHeaderCell when a different behavior is set. In this example, the SelectionMode is set to ColumnHeaderSelect, so clicking the DataGridViewColumnHeaderCell selects the contents of the column. To run this example, paste the code into a form that contains a DataGridView named dataGridView1 and ensure that all events are associated with their event handlers.

private void dataGridView1_ColumnHeaderMouseClick(
    object sender, DataGridViewCellMouseEventArgs e)
{
    DataGridViewColumn newColumn = dataGridView1.Columns[e.ColumnIndex];
    DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
    ListSortDirection direction;

    // If oldColumn is null, then the DataGridView is not sorted.
    if (oldColumn != null)
    {
        // Sort the same column again, reversing the SortOrder.
        if (oldColumn == newColumn &&
            dataGridView1.SortOrder == SortOrder.Ascending)
        {
            direction = ListSortDirection.Descending;
        }
        else
        {
            // Sort a new column and remove the old SortGlyph.
            direction = ListSortDirection.Ascending;
            oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
        }
    }
    else
    {
        direction = ListSortDirection.Ascending;
    }

    // Sort the selected column.
    dataGridView1.Sort(newColumn, direction);
    newColumn.HeaderCell.SortGlyphDirection =
        direction == ListSortDirection.Ascending ?
        SortOrder.Ascending : SortOrder.Descending;
}

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0

Community Additions

ADD
Show:
© 2014 Microsoft