【问题标题】:Sorting numeric strings [duplicate]对数字字符串进行排序[重复]
【发布时间】:2015-12-17 02:07:19
【问题描述】:

我在 中使用 DatagridView 来读取 csv 文件。
单击网格顶部的标题时,数据未正确排序。

比如应该排序为1,2,3,4,5,etc
但是,结果是1,10,2,20,etc

我想我需要将它从 string 转换为 int,但我不知道该怎么做。

这是我当前的代码:

try
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string csvPath = openFileDialog1.FileName;
        string rowValue;
       // int rowValue = int.Parse(??);
        string[] cellValue;
        dataGridView1.Rows.Clear();
        //dataGridView1.Columns.Clear();
        if (System.IO.File.Exists(csvPath))
        {
            System.IO.StreamReader fileReader = new StreamReader(csvPath);
            rowValue = fileReader.ReadLine();
            cellValue = rowValue.Split(',');

            for (int i = 0; i <= cellValue.Count() - 1; i++)
            {
                DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
                column.Name = cellValue[i];    //column name , value
                column.HeaderText = cellValue[i];
                dataGridView1.Columns.Add(column);
               // dataGridView1.Columns[].CellType = typeof(Int64);
            }                      
            while (fileReader.Peek() != -1)
            {
                rowValue = fileReader.ReadLine();
                cellValue =  rowValue.Split(',');
                dataGridView1.Rows.Add(cellValue);
            }
            fileReader.Dispose();
            fileReader.Close();
        }
        else

【问题讨论】:

    标签: c# c# string csv datagridview int


    【解决方案1】:

    尝试像这样在DataGridView 中注册一个比较器:

    private void CustomSortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        if(e.Column.Name != "CollumnName") return;
    
        var a = int.Parse(e.CellValue1.ToString());
        var 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;
    }
    

    并在DataGridView中注册排序器

    dataGridView1.SortCompare += CustomSortCompare;
    

    查看文档DataGridView.SortCompare Event

    【讨论】:

    • 好的,谢谢...我有新问题...第一列的标题正常 1,2,3,4,5,6,7,8,9,10 好!但其他人..有错误...
    • @Simkyujin 您可以在每个列中添加一个排序比较器,这样您就可以像 e.Column.Name != "CollumnName" 那样验证它是否是您想要的列,然后返回。如果它有帮助,请不要忘记有帮助的投票或将答案标记为正确。
    • 好的!我会试试的。。非常感谢!祝你有美好的一天!
    【解决方案2】:

    您可以使用此代码以字符串模式检测数字列,将它们转换为整数并对其进行排序:

    try {
    if (e.Column.Index == 2) {
        e.SortResult = Convert.ToInt32(e.CellValue1) < Convert.ToInt32(e.CellValue2) ? -1 : 1;
        e.Handled = true;
        }
    
      } catch (Exception ex) {
      }
    

    在上面的示例中,数字位于 Datagridview 的第 2 列中。 将代码放入grid的SortCompare事件中。

    【讨论】:

    • emm.....不调整..对不起,我是 C# 初学者
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2013-06-08
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    相关资源
    最近更新 更多