This question is closely related to these two (this and this) but I don't think they give a satisfying answer.
I have a DataGridView
(i.e. a table) with several columns (DataGridViewTextBoxColumn
) of different data types: string, integers and floats. When I click on their respective header, each should be sorted according to their type: string alphabetically and numerical values numerically. I have, simply put, the following code:
private System.Windows.Forms.DataGridView grid;
private System.Windows.Forms.DataGridViewTextBoxColumn stringColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn doubleColumn;
private System.Windows.Forms.DataGridViewTextBoxColumn intColumn;
stringColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
doubleColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
intColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
grid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
stringColumn,
doubleColumn,
intColumn});
However, since the default representation is string
, the numerical values also get sorted alphabetically, for example like this:
1, 11, 2, 3, 42, 5
Apparently, as an easy way of getting around this, according some threads (e.g. here and here), the following should work immediately solve the problem:
doubleColumn.ValueType = typeof(double);
intColumn.ValueType = typeof(int);
However, this solution simply doesn't work in my project: values are still sorted alphabetically. So the question is: why not? In the Debugger, I could see that the value type actually changed to (in the double
case) System.Double
, so something is happening at least. But how can I make sure that it actually sorts it accordingly, without writing my own sorter?
If you are using a DataTable
then you have to set the DataType
on the DataColumn
. Setting ValueType
on the DataGridViewTextBoxColumn
won't help.
You can set it when creating it:
table.Columns.Add("Number", typeof(int));
You can handle the event SortCompare
to change how the sorting is done, like this:
private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e) {
//Suppose your interested column has index 1
if (e.Column.Index == 1){
e.SortResult = int.Parse(e.CellValue1.ToString()).CompareTo(int.Parse(e.CellValue2.ToString()));
e.Handled = true;//pass by the default sorting
}
}
NOTE: The above code supposes your cell values are convertible to int.
You said your DataGridView
doesn't have DataSource
assigned, that means you Add
the rows manually, so I think you should use numeric
values instead of string
for your cells. That would make the sorting work as you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With