如何排序DataGridView?

时间:2013-11-20 20:25:24

标签: c# winforms sorting datagridview rows

我想按如下方式对datagridview进行排序

enter image description here

当我清除任何行时,datagridview就像这样

enter image description here

结果datagridview应该是这样的

enter image description here

我试了一下但是没有用

    foreach (DataGridViewRow rw in dataGridView1.Rows.Cast<DataGridViewRow>())
    {
            for (int i = 0; i < rw.Cells.Count; i++)
            {
                rw.Cells[i].Value = rw.Cells[i + 1].Value;
            }
    }

1 个答案:

答案 0 :(得分:2)

以这种方式更新网格可能会导致性能不佳,尤其是当您有数千行和数十列时。这段代码对您有用,但是您的需求确实很奇怪,在大多数专业项目中可能都不会遇到:

//First we need to get all the non-empty cell values in some List<string>
var cells = dataGridView1.Rows.Cast<DataGridViewRow>()
              .Where(row=>!row.IsNewRow)
              .SelectMany(row=>dataGridView1.Columns.Cast<DataGridViewColumn>()
                               .Select(col=>row.Cells[col]))
              .OrderBy(cell=>cell.ColumnIndex)
              .ThenBy(cell=>cell.RowIndex)
              .Where(cell=>Convert.ToString(cell.Value)!="").ToList();
//update the cells to make the grid look like sorted
for(int i = 0; i < dataGridView1.ColumnCount; i++){
  for(int j = 0; j < 8; j++){
    if(dataGridView1.Rows[j].IsNewRow) continue;
    int k = i*8+j;
    dataGridView1[i,j].Value = k < cells.Count ? cells[k] : null;
  }
}