【问题标题】:Custom sorting order - DataGridView自定义排序顺序 - DataGridView
【发布时间】:2015-05-12 09:12:35
【问题描述】:

是否可以在 datagridview 中对其进行排序,而无需在 + 之后将数据填充为 3 个值。
数据类型为字符串,datagridview 列为文本。

10:10+01
10:10+100
10:10+110
10:10+10

应该这样排序

 10:10+01
 10:10+10
 10:10+100
 10:10+110

也许将排序模式更改为程序化可能会有所帮助?

任何意见将不胜感激

编辑:将数据复制到 dt 然后与数据视图绑定的示例。

DataTable dtTest = new DataTable();
dtTest.Columns.Add("Column1", typeof(string));
dtTest.Rows.Add("10:11+1");
dtTest.Rows.Add("10:11+101");
dtTest.Rows.Add("10:11+101");
dtTest.Rows.Add("10:11+2");
dtTest.Rows.Add("10:11+200");
dtTest.Rows.Add("10:10+1110");
DataView dvTest = new DataView(dtTest);
dataGridView1.DataSource = dvTest;

排序示例

10:10+1110
10:11+1
10:11+101
10:11+101
10:11+2
10:11+200

【问题讨论】:

  • 要么创建一个列,修改数据以使用正常排序,要么,是的,更改为程序化。听起来比它更难..据我所知,只有 1-3 个函数..
  • 您的数据已更改,但在稍微扩展填充后,以下解决方案将起作用..但是您之前没有提到 DGV 是 DataBound!

标签: c# winforms datagridview datatable


【解决方案1】:

自定义排序未绑定的 DataGridview

不确定您的数据,但从字面上看,这将为 unbound DataGridView DGV:

首先你需要连接一个SortCompare 处理程序,可能是这样的

 DGV.SortCompare += new DataGridViewSortCompareEventHandler(  this.DGV_SortCompare);

如有必要,您可以在您的列上调用它(或让标题单击完成工作):

 DGV.Sort(DGV.Columns[yourColumn], ListSortDirection.Ascending);

这是 SortCompare 事件代码。它使用简单的字符串操作通过用零填充最后一部分来创建可排序的版本。

 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;
 }

全面讨论了对 DGV 进行排序的三种方法here on MSDN. - 显然这是解决您的问题的最简单方法。也相当灵活:您也可以使用e.columnIndex 参数为其他列创建单独的比较字符串..

如果其他列不需要特殊的排序代码,您应该将此行插入SortCompare的开头:

  if (e.Column.Index != yourColumn) return;

自定义排序数据绑定DataGridView

更新:由于您已将问题更改为 DataBound DGV,因此对于这种情况,这里有一个类似的解决方案:

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;
}

此解决方案假定您的DataSourceDataTable DT,并将创建一个名为“TempSort”的临时列`并用准备好的数据值版本填充它;它将升序排序。

对于排序,我们使用BindingSource

要动态控制右列(此处称为“yourcolumn”)以及排序顺序,您必须自己编写一些代码,响应ColumnHeaderClick...

【讨论】:

  • 感谢您输入 TaW 和示例。我用示例数据编辑了我的帖子。我已经添加了 SortCompare 事件,但是当我单击列标题时它似乎没有触发。我添加了事件并强制使用“dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Ascending);”进行排序但它仍然没有触发 DGV_SortCompare
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 2010-09-30
  • 2010-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多