Reputation: 860
(using .Net 3.5)
I have a datagridview that is bound to a list of objects and AllowUserToAddRows=True
, but the objects don't have empty constructors. I think because of that the grid's new row wasn't appearing. So then I handled the binding source "AddingNew" event to programmatically insert the necessary contructor arguments:
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
So now the new row appears in the datagridview. However, the first column happens to be a button column, and clicking on the new row button cell apparently doesn't trigger a new row. So then I tried to handle the cell click and force the binding source to create a new row:
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
But now the datagridview creates TWO new rows when the user clicks the button cell! I have no idea why. How can I make the datagridview create just one new row (ie add a binded object) when a user clicks on a new row's button cell?
(Btw, I really like the datagridview's AllowUserToAddRows feature as displaying a new row seems more visually elegant to me than putting "Add" & "Remove" buttons on the form or the like, which is why I'm trying to power through these problems)
Upvotes: 0
Views: 893
Reputation: 860
Well after an absurd amount of time spent fighting datagridview, I finally stumbled upon what appears to be a workable answer. This was actually suggested in a forum but I've lost the link. By calling bindingsource CancelEdit you prevent the AddNew that datagridview is performing behind the scenes. It's still got a few quirks but is generally okay:
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
Upvotes: 1