开发者

DataGridView Cell Customization

I would like to create a cell for the datagridview that would accept a Int64 value in order to sort.

Additionally that cell will display an extra value that is the difference of the current value with a reference value I have outside the datagridview.

I could do it as string but the sorting will not be correctly handled because it w开发者_运维知识库ould look like 1, 10, 11, 2.... and so on.

So I thought that if I could create a custom cell and define the cell value the long and display a string it would be great... but I'm not sure if this can be accomplished....

Does someone know how can this be accomplished in a simple way? Note that I am loading the datagridview manually but I am defining the column types to allow sorting.


One fairly easy way to do this is to use the DataGridView's SortCompare event. Use the event to check that the column being sorted displays your custom data and if so extract the number portion of that data and do your sort on it.

Below I have an example:

private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e) {
    if (e.Column.Index == 1) {  // This is your custom data's column.
        // Extract the numeric values from the cells being compared for the sort.
        // BEWARE: code assumes you'll always be able to extract a long from the cell contents.
        long cell1NumericValue = Int64.Parse(e.CellValue1.ToString().Split(' ')[0]);
        long cell2NumericValue = Int64.Parse(e.CellValue2.ToString().Split(' ')[0]);

        // Compare these numeric values to determine how to sort.
        e.SortResult = cell1NumericValue.CompareTo(cell2NumericValue);

        e.Handled = true;
    }
}

Assumptions:
- that the column with your custom data is at column index 1
- that your custom data consists of a number followed by at least one space

My code also assumes that the conversion of the cells' value will never throw an error. It's possible that your data includes values that would cause this conversion to fail. What you could do in that case is validate your data before the conversion (that it's not null, etc.) and if of the validation fails set the cell's numeric value for sorting purposes to -1 or something so it's always lower than valid values in other cells. (I hope that made sense).

Applying these types of sorts is pretty well described in this MSDN article. You'll probably want to take a look. One of the examples show what you can do in the case of ties (the example shows sorting on another column as the sort tiebreaker).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜