How to empty the cells of a DataGridView in C#?
我已经在网上发现了类似的问题。虽然我还没有找到一个有效的答案。
所以我在使用Visual Studio 2008的Windows窗体应用程序中工作。语言是C语言
我有一个未绑定到数据源的DataGridView。
所以:
| 1 | MyDataGridView.DataSource = null; | 
不会工作…
我也试过了
| 1 | MyDataGridView.Rows.Clear(); | 
但这会删除所有自定义行。
所以我现在正在寻找一种方法来清空所有单元格(不包括标题单元格)的内容。所以除了细胞本身的内容,它不应该影响其他任何东西。
| 1 2 3 4 5 6 7 | for (int i = 0; i < MyDataGridView.Columns.Count ;i++ ) { for (int j = 0; j < MyDataGridView.Rows.Count; j++) { MyDataGridView.Rows[j].Cells[i].Value = DBNull.Value; } } | 
我相信使用Linq可以使它更清晰,特别是对于隐式类型:
| 1 2 3 4 |     foreach (var cell in from DataGridViewRow row in dgv.Rows from DataGridViewCell cell  in row.Cells select cell){ cell.Value = string.Empty; } | 
pieter888的代码对我不起作用,我发现的代码是
| 1 2 3 4 5 | int cnt=dataGridView1.Rows.Count; for (int i = 0; i < cnt; i++) { dataGridView1.Rows.Remove(dataGridView1.Rows[0]); } | 
我只是自己弄明白了怎么做,我只是在桌子上循环,清除我遇到的每一个细胞。
注意:"dgusers"是我的DataGridView的名称
| 1 2 3 4 5 6 7 | for (int i = 0; i < dgUsers.Columns.Count ;i++ ) { for (int j = 0; j < dgUsers.Rows.Count; j++) { dgUsers.Rows[j].Cells[i].Value =""; } } | 
我敢打赌,有更好的方法可以做到这一点,这看起来可能有点草率,但它确实做到了。不过,我想听听一个更好的解决方案,它可以清除数据。
可以使用清除整个网格
| 1 | gridviewname.columns.clear(); |