ferzle
ferzle

Reputation: 103

Sharing a DataSet among different forms in C#

I have created a DataSet with multiple tables. I use a few tables on one form, and then 2 other tables on 2 other forms. When I try to do the binding of the data, I cannot figure out how to have all 3 forms refer to the same DataSet object. In the interface (Visual Studio Express 2013) I can select from the Project Data Sources list and get my MainDataSet class and then select whichever table I want. But if I do this, I get a new object. None of the other options seem to allow me to pick an already existing object. I thought I used to see an option to pick my MainDataSet object from somewhere, but I don't currently see that option and even so, it didn't allow me to select a table anyway.

I know I could look closer at the binding code and figure out how to make this work, but since some of that code is in the Designer file, I can't modify it so it seems the best I can do if I do this is replace what it did with new bindings. And it seems like I shouldn't have to do this. There HAS to be a way to do this in the Visual Studio GUI.

Upvotes: 1

Views: 2002

Answers (2)

ferzle
ferzle

Reputation: 103

Based on SLaks' suggestion, here is what I did.

  1. I dragged a BindingSource onto a form and named it sharedDataSource.
  2. In the Properties of the BindingSource I set the DataSource by selected MyDataSet class under the Project Data Sources heading. I believe this created the DataSource object and bound it to the BindingSource.
  3. In the designer I chose the data source for the the DataGridView objects by selecting sharedDataSource and then the appropriate table under that.
  4. For the DataGridViews in the second form I selected Other Data Sources-->Project Data Sources-->MyDataSet.
  5. I created a constructor for the second form that takes a MyDataSet object as a parameter. In the constructor I set both SomethingOrOtherBindingSource.DataSource and mainDataSet to the paramater. I think the former is required, but the latter may only be required if you refer to it in your code.
  6. When I create the second form (from the first form), I passed in sharedDataSource to the constructor.

So in the designer a data source is bound to the grid and you can use the designer to do whatever you need to (e.g. change column sizes, etc.), but when the program is run, the data source is changed to be the shared one. It seems to work.

Upvotes: 1

SLaks
SLaks

Reputation: 888185

You should create a BindingSource in the designer, then set its source to the DataSet in the designer.

You can then change your form's constructor to set the BindingSource's source to a shared DataSet.

Upvotes: 1

Related Questions