Datagridview一次添加两个新行

时间:2011-11-05 18:33:49

标签: .net winforms data-binding datagridview

(使用.Net 3.5) 我有一个datagridview绑定到对象列表和AllowUserToAddRows=True,但对象没有空构造函数。我想因为网格的新行没有出现。然后我处理了绑定源“AddingNew”事件,以编程方式插入必要的构造函数参数:

 Private _Codes As BindingList(Of CodeSelector)
 Private WithEvents _bs As New BindingSource

    _Codes = New BindingList(Of CodeSelector)
    _bs.DataSource = _Codes
    _bs.AllowNew = True
    Me.dgvGraphs.DataSource = _bs


 Private Sub _bs_AddingNew(ByVal sender As Object, ByVal e As System.ComponentModel.AddingNewEventArgs) Handles _bs.AddingNew
    e.NewObject = New CodeSelector({default contructor arg's here})
End Sub

所以现在新行出现在datagridview中。但是,第一列恰好是按钮列,单击新行按钮单元显然不会触发新行。然后我尝试处理单元格单击并强制绑定源创建一个新行:

Private Sub dgvGraphs_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvGraphs.CellClick
        Dim dgv = DirectCast(sender, DataGridView)
        If e.ColumnIndex = ColEdit.Index AndAlso e.RowIndex = dgv.NewRowIndex Then
            _bs.AddNew()
        End If
End Sub

但是现在,当用户点击按钮单元格时,datagridview会创建两个新行!我不知道为什么。当用户点击新行的按钮单元格时,如何使datagridview只创建一个新行(即添加绑定对象)?

(顺便说一句,我真的很喜欢datagridview的AllowUserToAddRows功能,因为显示一个新行对我来说看起来比在表单上添加“添加”和“删除”按钮更优雅,这就是为什么我要尝试通过这些问题解决问题)

1 个答案:

答案 0 :(得分:1)

在花费了大量时间来对抗datagridview之后,我终于偶然发现了一个看似可行的答案。这实际上是在一个论坛中提出的,但我已经失去了链接。通过调用bindingsource CancelEdit可以阻止datagridview在幕后执行的AddNew。它仍然有一些怪癖但通常没问题:

 Private Sub dgvGraphs_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvGraphs.CellClick
        Dim dgv = DirectCast(sender, DataGridView)
        If e.ColumnIndex = ColEdit.Index Then
            If e.RowIndex = dgv.NewRowIndex Then
                _bs.AddNew()
                _bs.CancelEdit()
            E 
        End If
End Sub