【问题标题】:Prevent DataGridView from adding empty row to BindingSource防止 DataGridView 向 BindingSource 添加空行
【发布时间】:2019-08-22 21:07:30
【问题描述】:

我有一个DataGridView (AllowUserToAddRows = true, EditMode = EditOnKeystrokeOrF2) 绑定到BindingSource(绑定到DataTable)。 我的DataGridView 有一个ComboBoxColumn,我可以在其中选择国家/地区。

DataGridViewtrue 上有AllowUserToAddRows,因为用户应该能够通过从每个DataGridView 都有的空白“新行”中选择一个国家来添加行。

问题是每当我用鼠标单击空行时,它都会将新行添加到我的BindingSource。但是,DataGridView 的新“空白”行只有在您从前一个(单击的)新行中实际选择一个国家/地区时才会出现。

因此,用户不知道他添加了新行。该行将DBNull.Value 设为Country,因为没有选择任何内容。尝试保存时会抛出错误,因为Country 不能为空。

所以我需要防止在从ComboboxColumn 中选择一个值之前将新行添加到BindingSource

CountryDBNull 时,我尝试RowValidating-Event 取消编辑,但它阻止我离开新行。这不是我想要的。

基本上,我认为我有this 的问题,没有“关闭表单”部分。

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    数据网格视图中存在的“空白”行仅用于添加新行,它在数据源中不存在,直到您实际单击那里。一旦您对该“新行”区域进行编辑并移出该行,datagridview 将添加另一个“新行”区域。我的建议是在保存之前添加一些验证并排除任何未通过验证的行。

    【讨论】:

      【解决方案2】:

      在我调用我的 Save 方法(在我的 DataAdapter 上调用 Update)之前使 DataGridView 失去焦点使空行从我的 BindingSource 中消失。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-12
        • 2016-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多