【问题标题】:Deleting Item from BindingSource Leaves Blank Row in DataGridView Which it is Connected to as DataSource从 BindingSource 中删除项目会在作为 DataSource 连接的 DataGridView 中留下空白行
【发布时间】:2021-12-28 20:25:17
【问题描述】:

我正在开发一个 winforms 项目,其中有一个绑定源连接到 DataGridView。添加和更新工作就像一个魅力,但是当我删除一个项目时,它会留下一个空白行。在此之后添加的任何项目都将添加到空白行之后。我尝试刷新 DataGridView,将 AllowUserToAddRows 设置为 False,并在 StackOverflow 上找到了一些其他建议。任何帮助将不胜感激来解决这个问题。谢谢。

这是我目前的代码。

// Setting the binding source
IList<Contact> contacts = getContacts();
contactBindingSource.DataSource = contacts;

// removing the item
var currentContact = (Contact)dataGridView1.CurrentRow.DataBoundItem;
contactBindingSource.Remove(currentContact);

【问题讨论】:

  • 发布的代码有效。可能需要给我们更多信息。
  • @LarsTech 它确实从有效的 Datagrid 中删除了该行,但它在其位置留下了一个空白行。如果我将一个新联系人添加到我的绑定源,它会在该空白行之后添加数据网格中的新行。现在,如果您的意思是您没有得到空白行,那么我将仔细查看我的代码。谢谢。
  • 这正是我要说的。使用您发布的代码,该行在我的网格中消失了。它不会空白。尝试在新项目中重现问题。
  • @LarsTech,可以的
  • 从一个新项目开始就可以了。唯一的区别是我让联系人从另一个表单添加为 POCO。当这种情况发生时喜欢它,谢谢你至少看到这个。回到绘图板。

标签: c# winforms


【解决方案1】:

您可以先从 gridview 中删除项目,然后从数据源中删除

 int x = dataGridView1.CurrentRow.Index;
 dataGridView1.Rows.Remove(DataGridView1.Rows[x]); 
 contactBindingSource.DataSource = dataGridView1.DataSource as DataTable;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    相关资源
    最近更新 更多