如何使用 C# 以编程方式从 Windows 窗体中的数据网格视图中删除单元格?



我需要根据某些条件从Windows窗体的数据网格视图中删除一个单元格。

下面是我的代码。

private void grdvTest_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
try
{
var grdv = sender as DataGridView;
foreach (DataGridViewRow row in grdv.Rows)
{
DataGridViewCell BookButtonCell = row.Cells[0];
ViewModelMyItem item = row.DataBoundItem as ViewModelMyItem;
if (item.IsDeleted)
{
row.Cells.Remove(BookButtonCell);
}
}
}
catch (Exception ex)
{
throw ex
}
}

错误:

row.Cells.Remove(BookButtonCell);

集合已属于 DataGridView 控件。此操作不再有效。

将数据源绑定到 gridview 控件后,无法删除单元格,但如果要通过初始化如下所示的新单元格来隐藏该单元格或Accessible Object以不同的方式处理它。

rowdata.Cells[6] = new DataGridViewTextBoxCell();

这将覆盖您的现有单元格。

最新更新