Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The first time I read this, I totally missed the part about sorting by <em>multiple</em> columns simultaneously (my fault, not yours; the question was perfectly clear).</p> <p>If that's the case, you are going to have to write the code that handles this yourself. The provided <code>DataGridView</code> control doesn't support multi-column sorting by default. Fortunately, others have already done a lot of the work to implement this for you. Here are a few samples:</p> <ul> <li><a href="http://www.codeproject.com/KB/grid/multicolumn_sort.aspx" rel="noreferrer">DataGridView Multi-column Sort</a> (CodeProject)</li> <li><a href="http://www.codeproject.com/KB/grid/Multiple_columns_sorting.aspx" rel="noreferrer">How To Allow To Sort By Multiple Columns in Custom Data Binding</a> (CodeProject)</li> </ul> <p>Alternatively, if you bind your <code>DataGridView</code> to a data source, that data source can be sorted on multiple columns and the <code>DataGridView</code> control will respect that sorting. Any data source that implements <code>IBindingListView</code> and exposes a <code>Sort</code> property will work for multi-column sorting.</p> <p><br> However, regardless of the route that you choose to enable multi-column sorting, you aren't going to have much success in coercing the <code>DataGridView</code> to display the sort arrow glyph on multiple columns. The easiest solution here is to custom draw only the column headers to provide your own sort glyph.</p> <p>To do this, attach a handler to the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellpainting.aspx" rel="noreferrer"><code>DataGridView.CellPainting</code> event</a> and check for a <code>RowIndex</code> of -1 (indicating a column header). There's a full sample of owner-drawn column headers <a href="http://www.codeproject.com/KB/vb/GradientColumnheader.aspx" rel="noreferrer">here</a>. I strongly recommend sticking with the conventional arrow icon, but once you go this route, the options are truly unlimited. You can make your column headers look like anything you want, and even indicate the relative weight of each column in the sort order using different icons.</p> <p>You can also choose to derive a new class from <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumnheadercell.aspx" rel="noreferrer"><code>DataGridViewColumnHeaderCell</code></a> and override its <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumnheadercell.paint.aspx" rel="noreferrer"><code>Paint</code> method</a>. This is probably a cleaner, more object-oriented way of accomplishing the same thing.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload