[英]How to empty the cells of a DataGridView in C#?
I've found questions similar on SO already, all over the net actually.我已经在 SO 上发现了类似的问题,实际上是在整个网络上。 Though I haven't found a working answer yet.
虽然我还没有找到有效的答案。
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 not bound 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.
所以它不应该影响其他任何东西,但单元格本身的内容。
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;
}
}
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.
但我想听到一个更好的解决方案来清除数据。
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;
}
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]);
}
您可以使用清除整个网格
gridviewname.columns.clear();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.