我有一个 WinForms 应用程序,其中的 DataGridView 设置为默认设置,以允许用户添加行。但我也想以编程方式删除行。
当我运行该函数时
dataGridView.Rows.Clear()
什么也没有发生 - 行保留在 DataGridView 中。
我已经更改了编辑模式、删除了数据源并刷新了:
dataGridView.EditMode = DataGridViewEditMode.EditProgrammatically;
dataGridView.DataSource = null;
dataGridView.Rows.Clear();
dataGridView.Refresh();
dataGridView.EditMode = DataGridViewEditMode.EditOnKeystroke;
但是,用户添加的行在 DGV 中仍然可见。我怎样才能删除这些行?,
编辑: DGV 截图:
您是否尝试迭代 dataGridViewError.Rows 集合并逐一删除?
foreach (DataGridViewRow row in dataGridViewError.Rows)
{
try
{
dataGridViewError.Rows.Remove(row);
}
catch (Exception) { }
}
您的问题是为什么 dataGridView.Rows.Clear() 不起作用,答案是您发布的代码正在作用于
DataSource
属性,但该属性似乎未正确设置(或使用) .
首先,您需要一个充当行的 Model 的类(换句话说,它声明您想要在
DataGridView
中拥有的列)。创建属性 {get;set;}
意味着用户将能够在 DataGridView
中编辑这些属性。
public class Record
{
public string Licznic { get; set; }
public string Procent { get; set; }
}
DataGridView
易于使用的原因在于它被设计为基于此类“自动”配置自身。只需创建一个 BindingList<Record>
并通过覆盖主窗体类中的 DataSource
将其附加到 OnHandleCreated
属性: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;
}
如果运行此代码,您会得到以下结果:
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();
dataGridView.DataSource = null ;