简体   繁体   English

如何在不删除列标题的情况下清除所有行datagridview c#

[英]How to clear all the rows without removing column header datagridview c#

I have a datagridview bound to a datasource, all headers are added to the columns collection with a datapropertyname set. 我有一个绑定到数据源的datagridview,所有标头都添加到具有datapropertyname设置的列集合中

When I clear the datagridview using 当我使用清除datagridview时

DataGridView1.DataSource = null;

The headers also disappear and when I fill the datagridview again the header texts are the database column names. 标头也消失了,当我再次填充datagridview时,标头文本就是数据库列名。

Before refilling datagridview 在重新填充datagridview之前

After clearing and refilling the datagridview 清除并重新填充datagridview之后

I do this to fill my datagridview 我这样做是为了填充我的datagridview

    MyDataGridView.DataSource = MyDatabase.MyTable.Select(rows => new
                {
                    ProductName = rows.Product.Name,
                    Quantity = rows.Quantity,
                    SalePrice = rows.SalePrice,
                    SubTotal = rows.Quantity * rows.SalePrice
                }).ToList();

So, is it possible to clear all rows without removing column header? 那么,有可能在不删除列标题的情况下清除所有行吗?

您可以使用此命令清除所有行:

MyDataGridView.Rows.Clear();

It works for me: 这个对我有用:

var dt = MyDataGridView.DataSource as DataTable;
dt.Rows.Clear();
MyDataGridView.DataSource = dt;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM