如何在 C# 中清空 DataGridView 的单元格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1818848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to empty the cells of a DataGridView in C#?
提问by Pieter888
I've found questions similar on SO already, all over the net actually. Though I haven't found a working answer yet.
我已经在 SO 上发现了类似的问题,实际上是在整个网络上。虽然我还没有找到有效的答案。
So I'm working in a windows form application using Visual studio 2008. Language is C#
所以我正在使用 Visual Studio 2008 在 Windows 窗体应用程序中工作。语言是 C#
I have a DataGridView that is notbound to a DataSource.
我有一个未绑定到数据源的 DataGridView 。
so:
所以:
MyDataGridView.DataSource = null;
wont work...
行不通...
I've also tried
我也试过
MyDataGridView.Rows.Clear();
But this removes all my custom made rows.
但这会删除我所有的自定义行。
So I'm now looking for a way to just empty the contents of all cells (not including header cells). So it shouldn't affect anything else but the contents of the cells itself.
所以我现在正在寻找一种方法来清空所有单元格的内容(不包括标题单元格)。所以它不应该影响其他任何东西,但单元格本身的内容。
采纳答案by Pieter888
I just figured out how to do it myself, I simply loop trough the table, clearing every cell I encounter.
我只是想出了如何自己做,我只是在表格中循环,清除我遇到的每个单元格。
note: "dgUsers" is the name of my DataGridView
注意:“dgUsers”是我的 DataGridView 的名称
for (int i = 0; i < dgUsers.Columns.Count ;i++ )
{
for (int j = 0; j < dgUsers.Rows.Count; j++)
{
dgUsers.Rows[j].Cells[i].Value = "";
}
}
I bet there is a better way to do this and this might look a bit sloppy but it does the job. Yet I'd like to hear a better solution that clears the data.
我敢打赌有更好的方法来做到这一点,这可能看起来有点草率,但它确实可以。但我想听到一个更好的解决方案来清除数据。
回答by Blazen
the code by pieter888 didnt worked for me the code i figured out was
pieter888 的代码对我不起作用 我发现的代码是
int cnt=dataGridView1.Rows.Count;
for (int i = 0; i < cnt; i++)
{
dataGridView1.Rows.Remove(dataGridView1.Rows[0]);
}
回答by Ryan K
you can clear the entire grid by using
您可以使用清除整个网格
gridviewname.columns.clear();
回答by Rene Alberto Zurita Sanchez
I believe that using LINQ you can make it cleaner, specially with implicit types:
我相信使用 LINQ 可以使它更干净,特别是使用隐式类型:
foreach (var cell in from DataGridViewRow row in dgv.Rows from DataGridViewCell cell
in row.Cells select cell){
cell.Value = string.Empty;
}
回答by Evgeny
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;
}
}