Adding new row to DataGridView bound to Custom Object

G

Guest

I have a DataGridView bound to a collection of Custom Objects. I have
enabled adding new rows, but since my object does not have a public
constructor (it uses a factory method), I get an error when I attempt to
enter the new row. My guess is that I need to override some method so that I
can create the object for the grid. But for the life of me, and I can't find
it. Can someone point me in the right direction?
 
B

Brendon Bezuidenhout

Terry,

Have you tried just inserting a new row into the data source of the
DataGridView object?

Brendon
 
G

Guest

Hi,
No, I haven't. Are you suggesting that I pre-create a new object and
have it in the grid just in case the user wants to add one? I suppose that
that could be made to work. I still have to believe that there is some
method that I can override or some event I can subscribe to, that would allow
me to create the object for the grid.
 
B

Brendon Bezuidenhout

Terry,

No what you want to do do is inefficient... when they add a new "row" as it
were you create a new datadow and add that data row to the datasource which
is a DataTable (sucking it from my head now so could be wrong on the type).
Then when they close/save then you save and add the new row as per normal to
your DB... Why don't you look into the BindingManager and BindingSource also
:) it will help and might make you rethink things slightly.

Brendon

Terry said:
Hi,
No, I haven't. Are you suggesting that I pre-create a new object and
have it in the grid just in case the user wants to add one? I suppose
that
that could be made to work. I still have to believe that there is some
method that I can override or some event I can subscribe to, that would
allow
me to create the object for the grid.
 
G

Guest

Ok, turned out to be fairly easy - once I figured out where to do it!
The grid is bound to a bindingsource which raises a 'AddingNew' event. So
the code looks like...
Private Sub LogListBindingSource_AddingNew(ByVal sender As Object, ByVal e
As System.ComponentModel.AddingNewEventArgs) Handles
LogListBindingSource.AddingNew

e.NewObject = Log.Create(Id)

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top