2013-11-20 86 views
0

我想整理我的datagridview如下如何对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; 
      } 
    } 
+2

这是不排序的GridView控件,它完全改变你的GridView。 –

+0

是的,就像我只想要 – Anjali

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

通过使用这个我的datagridview没有正确更新名称将像这样“DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 0}”的第一行,“DataGridViewTextBoxCell {ColumnIndex = 0,RowIndex = 2}”像这样更新 – Anjali

+0

上面的一个我清除了,但它只取7行而不是8行。 – Anjali

+0

rowcount固定它只有8行。 – Anjali