我有一个带有默认设置的WinForms应用程序,其DataGridView集允许用户添加行。但是我也想以编程的方式删除行。
当我运行函数dataGridView.Rows.Clear()
时,什么都不会发生--行保留在DataGridView中。
我甚至更改了编辑模式,删除了数据源,并刷新了:
dataGridView.EditMode = DataGridViewEditMode.EditProgrammatically;
dataGridView.DataSource = null;
dataGridView.Rows.Clear();
dataGridView.Refresh();
dataGridView.EditMode = DataGridViewEditMode.EditOnKeystroke;
但是,用户添加的行在DGV中仍然可见。我怎样才能移除这些行?
编辑:DGV的截图:
发布于 2022-06-09 10:38:51
您试过迭代dataGridViewError.Rows集合并逐个删除吗?
foreach (DataGridViewRow row in dataGridViewError.Rows)
{
try
{
dataGridViewError.Rows.Remove(row);
}
catch (Exception) { }
}
发布于 2022-06-09 13:50:20
您的问题是为什么dataGridView.Rows.Clear()不能工作,答案是您的已发布代码对DataSource
属性进行了操作,但是该属性似乎没有被正确设置(或使用)。
首先,您需要一个类作为行的模型(换句话说,它声明您希望在DataGridView
中拥有的列)。创建属性{get;set;}
意味着用户将能够在DataGridView
中编辑这些属性。
public class Record
{
public string Licznic { get; set; }
public string Procent { get; set; }
}
使automatically易于使用的是,它被设计为基于这个类来配置自己的DataGridView
。只需创建一个BindingList<Record>
并通过在主窗体类中重写OnHandleCreated
将其附加到DataSource
属性:
BindingList<Record> DataSource = new BindingList<Record>();
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
// Attach the DataSource to your DataGridView
// Now changes to source records refresh in the view.
dataGridView1.DataSource = this.DataSource;
// Adding one or more records will generate the columns.
DataSource.Add(new Record { Licznic = "ABC123", Procent = "XYZ" });
DataSource.Add(new Record { Licznic = "DEF456", Procent = "PQR" });
// Use string indexer to get a column
dataGridView1.Columns[nameof(Record.Licznic)].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns[nameof(Record.Licznic)].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
如果运行此代码,就会得到以下内容:
当单击UI上的clear按钮时,它现在在DataSource
上工作,而不是UI,您会发现这非常有效:
private void buttonClear_Click(object sender, EventArgs e)
{
DataSource.Clear();
}
编辑
根据数据网格视图被加载为空的注释,在OnHandleCreated
中进行这个小的更改以实现初始状态:
// Adding one or more records will generate the columns.
DataSource.Add(new Record { Licznic = "", Procent = "" });
// Based on your comment that the DataGridView is "Loaded Empty"
// you would want to clear this record immediately after the
// automatic configuration has taken place.
DataSource.Clear();
https://stackoverflow.com/questions/72558745
复制相似问题