【问题标题】:How to sort string as numbers in DataGridView如何在 DataGridView 中将字符串排序为数字
【发布时间】:2015-09-28 22:10:42
【问题描述】:

我在 datagridview 中有带有特定数字的字符串列。它没有绑定。我想正确排序。默认的 DataGridView 排序不正确。

示例: Dgv 是这样排序的:

 - FS 752/08/2014
 - FS 752/06/2015
 - FS 751/12/2013
 - FS 751/08/2014
 - FS 751/06/2015

应该是这样的:

 - FS 752/06/2015
 - FS 751/06/2015
 - FS 752/08/2014
 - FS 751/08/2014
 - FS 751/12/2013

我怎样才能做到这一点?

【问题讨论】:

标签: c# .net vb.net sorting datagridview


【解决方案1】:

正如您所说,您没有使用DataSource,那么您可以尝试使用SortCompare event

当用户单击列以更改排序顺序时,或者当您以编程方式调用 Sort function 时,将调用此事件。

这是一个基本示例。我假设您要排序的是年(?)然后是月(?)然后是第一个数字:

private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{

    // Check if we are sorting by the special column.
    if (myDataGridView.Columns.Contains("My_Column") && e.Column == myDataGridView.Columns["My_Column"])
    {

        // Parse the special values (add validation if required).
        string[] parts1 = e.CellValue1.ToString().Trim().Split('/');
        int a1 = int.Parse(parts1[0].Split(' ')[2]);
        int b1 = int.Parse(parts1[1]);
        int c1 = int.Parse(parts1[2]);
        string[] parts2 = e.CellValue2.ToString().Trim().Split('/');
        int a2 = int.Parse(parts2[0].Split(' ')[2]);
        int b2 = int.Parse(parts2[1]);
        int c2 = int.Parse(parts2[2]);

        // Compare each value as required.

        // First compare the last value (year?)
        e.SortResult = c1.CompareTo(c2);

        // If equal, then compare second value (month?)
        if(e.SortResult == 0)
            e.SortResult = b1.CompareTo(b2);

        // Finally if still equal, then compare first value
        if(e.SortResult == 0)
            e.SortResult = a1.CompareTo(a2);

    }

}

注意:如果您不能确保每个单元格中的格式始终有效,那么您需要向此事件添加验证逻辑。例如,使用 int.TryParse() 并检查 null 值,并验证 string 拆分的长度。

【讨论】:

  • 完美!我已经使用了这个解决方案,只需稍微修改一下,它就很完美了!我很高兴,谢谢你:)
猜你喜欢
  • 2011-02-10
  • 1970-01-01
  • 2010-11-18
  • 2012-01-20
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
相关资源
最近更新 更多