Database Connection On Other Forms

HLeyes

Member
Joined
Feb 10, 2016
Messages
15
Programming Experience
10+
Hi all,

I can connect to and open a database on a single form. How can I access that same database connection on another form (which might be the editing form for a selected record from the first form)? Is there a way to make a database connection "public" to be viewed on all forms?

Thanks in advance,

HLeyes
 
A database connection is an object like any other, so you access it in more than one place in exactly the same way as you would for any other object. The thing is, in the scenario you describe, you should be acing the connection in more than one place. It's a mistake that a lot of people make and it complicates things for them. What you should do is:

1. Get the object to be edited from the first form and pass it to the second form.
2. Edit the object on the second form.
3. When the second form closes, update the database ON THE FIRST FORM.

Lots of people have a DataGridView on one form, edit a record and save it to the database on a second form and then wonder why the grid doesn't show the change. It's because they're doing it the wrong way around. They should be updating the grid first and then updating the database from that. Let's say that you have a DataGridView bound to a DataTable. You get the DataRow or DataRowView bound to the grid row you want to edit and pass it to the dialogue. The dialogue populates its controls and the user edits the data. If the user clicks OK, you simply push the data back from the controls to the DataRow or DataRowView. Because that row is bound to the grid, the grid will update automatically. Once the dialogue closes, the first form can then simply save the changes in the bound DataTable back to the database, either immediately or as a batch after multiple edits.
 
The thing is, in the scenario you describe, you should be acing the connection in more than one place.
I'm not sure exactly what words I intended to use there but what I wrote obviously doesn't make any sense. I presumably meant to say something like "you shouldn't be creating a connection in more than one place".
 
Back
Top Bottom