2013-11-20 90 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