Custom sorting an unbound DataGridview
Not sure about your data, but taking them literally this will do the job for an unbound DataGridView DGV
:
First you need to hook up a SortCompare
handler, maybe like this
DGV.SortCompare += new DataGridViewSortCompareEventHandler( this.DGV_SortCompare);
If necessary you can call it on your column (or let the Header click do the job):
DGV.Sort(DGV.Columns[yourColumn], ListSortDirection.Ascending);
This is the SortCompare event code. It uses simple string manipulation to create a sortable version by padding the last part with zeroes.
private void DGV_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
string s1 = e.CellValue1.ToString().Substring(0, 6) +
e.CellValue1.ToString().Substring(6).PadLeft(5, '0');
string s2 = e.CellValue2.ToString().Substring(0, 6) +
e.CellValue2.ToString().Substring(6).PadLeft(5, '0');
e.SortResult = s1.CompareTo(s2);
e.Handled = true;
}
There is a comprehensive discussion of three methods to sort a DGV here on MSDN. - Clearly this is the easiest one for your problem. Also rather flexible: You can use the e.columnIndex
parameter to create spearate comparison strings for other columns as well..
If other columns need no special sorting code you should insert this line to the beginning of the SortCompare
:
if (e.Column.Index != yourColumn) return;
Custom sorting a data bound DataGridView
Update: Since you have changed your question to a DataBound DGV, here is a similar solution for this case:
BindingSource BS = new BindingSource();
private void sortButton_Click(object sender, EventArgs e)
{
DT.Columns.Add("TempSort");
foreach (DataRow row in DT.Rows)
{
string val = row[yourcolumn].ToString();
row["TempSort"] = val.ToString().Substring(0, 6) +
val.ToString().Substring(6).PadLeft(5, '0');
}
BS.DataSource = DT;
BS.Sort = "TempSort ASC";
DT.Columns.Remove("TempSort");
DGV.DataSource = BS;
}
This solution assumes your DataSource
is a DataTable DT
and will create a temporary column called "TempSort"`and fills it with the prepared version of the data values; it will sort ascending.
For the sorting we use a BindingSource
.
To control the right column (here called 'yourcolumn
') dynamically as well as the sort order, you will have to write some code yourself, responding to the ColumnHeaderClick
...