【发布时间】:2019-07-10 19:55:40
【问题描述】:
我的 Windows 窗体应用程序中有一个DataGridView gridFilas,它有两列,第二列总是包含可以转换为整数的字符串。当我单击对其进行排序时,它被排序为字符串,结果如下:
1, 11, 2, 22
但我需要将其排序为整数,例如:
1, 2, 11, 22
我已经尝试了this question 的所有答案,但没有一个起作用,顺便说一句,接受的答案,它不起作用,因为SortCompare 事件没有被触发,因为this。
所以到目前为止我尝试的是添加一个ColumnHeaderMouseClick 并使用以下命令对其进行排序:
private void gridFilas_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
// this for loop has been added in a vain hope of converting all elements to integer to see if it works...
for (int i = 0; i < gridFilas.Rows.Count; i++)
{
string v = gridFilas.Rows[i].Cells[1].Value.ToString();
gridFilas.Rows[i].Cells[1].Value = Convert.ToInt32(v);
}
if (queuesSortedAscending)
{
gridFilas.Sort(gridFilas.Columns["Tamanho_Fila"], System.ComponentModel.ListSortDirection.Descending);
}
else
{
gridFilas.Sort(gridFilas.Columns["Tamanho_Fila"], System.ComponentModel.ListSortDirection.Ascending);
}
queuesSortedAscending = !queuesSortedAscending;
}
在创建时设置数据源(Form 的构造函数):
dsComponentes = new DataSet();
// ... more code
gridFilas.DataSource = dsComponentes.Tables["Queue"];
每当我向 DataSource 添加新行时,我都会确保它被解析为 int:
DataRow qlinha = dsComponentes.Tables["Queue"].NewRow();
qlinha["Nome_Fila"] = process;
qlinha["Tamanho_Fila"] = Int32.Parse(status);
dsComponentes.Tables["Queue"].Rows.Add(qlinha);
我也尝试过事先更改列的数据类型:
dsComponentes.Tables["Queue"].Columns["Tamanho_Fila"].DataType = typeof(int);
所以,我不知道还能做什么,我只需要将它作为整数而不是字符串来排序。欢迎任何解决方案。
【问题讨论】:
-
the second column always contains strings that can be converted to integersDGV 列是类型化的 - 使用整数列或使用自然排序的自定义排序器。关于这两个主题的大量文档和帖子