[英]How to Sort DataGridView?
我想按如下方式對datagridview進行排序
當我清除任何行時,datagridview就是這樣的
結果datagridview應該是這樣的
我試了一下,但它不起作用
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;
}
}
以這種方式更新網格可能會導致性能不佳,尤其是當您有數千行和數十列時。 這段代碼對您有用,但是您的需求確實很奇怪,在大多數專業項目中可能都不會遇到:
//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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.