[英]how to sort string as number in datagridview in winforms
我在datagridview中有數字的字符串列。它沒有綁定,我想按照我使用的數字排序
colid.ValueType = typeof(int);
grid.Sort(colid, ListSortDirection.Descending);
但是像字符串一樣排序,例如:
11
12
23
7
80
81
而預期的是
7
11
12
23
80
81
您可以在SortCompare
事件上注冊,例如:
private void customSortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
int a = int.Parse(e.CellValue1.ToString()), b = int.Parse(e.CellValue2.ToString());
// If the cell value is already an integer, just cast it instead of parsing
e.SortResult = a.CompareTo(b);
e.Handled = true;
}
...
yourGridview.SortCompare += customSortCompare;
...
我沒有檢查是否有效,但你明白了...;)
將值賦給列時,只需轉換為Int32即可
DataGridView.Cells["example"].Value= Convert.ToInt32(text);
它會正確排序
您的問題是您對字符串值進行排序。 加載列時,必須選擇列中的值類型:
dt.Columns.Add(“ColumnName”,typeof(int));
創建一個類,如:
class Sort : IComparer
{
public int Compare(object x, object y)
{
return -int.Parse((string)x).CompareTo(int.Parse((string)y)); //sort descending
//return int.Parse((string)x).CompareTo(int.Parse((string)y)); //sort ascending
}
}
並做
grid.Sort( new Sort() );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.