Perhaps this code will give you the ideal. First I set up the data:
DataTable dt = new DataTable(); dt.Columns.Add("DateOfBirth", typeof(DateTime)); dt.Rows.Add(new DateTime(1981, 10, 29)); dt.Rows.Add(new DateTime(1984, 8, 12)); dt.Rows.Add(new DateTime(1982, 9, 7)); bindingSource1.DataSource = dt; dataGridView1.DataSource = bindingSource1; dataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.Programmatic;
Now, using ColumnHeaderMouseClick, we will sort by the first column:
private SortOrder _sortDirection; private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.ColumnIndex == 0) { string sort = string.Empty; switch (_sortDirection) { case SortOrder.None: _sortDirection = SortOrder.Ascending; sort = "asc"; break; case SortOrder.Ascending: _sortDirection = SortOrder.Descending; sort = "desc"; break; case SortOrder.Descending: _sortDirection = SortOrder.None; sort = string.Empty; break; } dataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = _sortDirection; if (!string.IsNullOrEmpty(sort)) { bindingSource1.Sort = "DateOfBirth " + sort; } else { bindingSource1.RemoveSort(); } } }
Hope this helps!
source share