Reputation: 47
I am using VS 2010 and C# windows forms. I need the user to enter how many objects he has and how much each weights. I then need to process each one. I typically use for each datarow in row collection.
Question is i tried cleaning up some of my Very Nasty code (this is my first real project ever btw) I have one main class at ~5000 lines of code and would like to break up specific sets of modules into there own classes. The problem is when the user enters info i have to set up a dataset on the main form (DSObjects) and link a table grid view and a couple of entry boxes with an add button to it so the user can add the data they need. The issue I am having is when I run the code and break up the class into sub classes the dataset is wiped out on each new class.
Upvotes: 0
Views: 3165
Reputation: 103495
Keep in mind that a DataSet is actually a small (but complete) database in memory. While most applications just use it to transfer data from a database server to objects in the application, it has all the parts of a full database: multiple tables, which can be joined be relationships, which can have queries run against them.
With that in mind, just as you wouldn't have separate databases for each class, but instead have one used globally for the whole application, it is similarly quite reasonable to have one DataSet shared by all objects in the application.
Upvotes: 0
Reputation: 56697
Do not create a new instance of the data set in every class, but pass one instance around, like:
public class AnotherClass
{
private DataSet m_dataSet;
public AnotherClass(DataSet ds)
{
m_dataSet = ds;
}
}
When creating a new instance of AnotherClass
use:
AnotherClass ac = new AnotherClass(m_dataSet);
where m_dataSet
is again a member variable that references the data set - either passed to the calling class in the constructor, or (in case of the main class) being created somewhere in the code.
Only create the data set once, for example in the main class.
Another approach could be to use a singleton class that holds an instance to the data set. The singleton could then be accessed from lots of different objects.
A non-threadsafe sample would be:
public class DataHolder
{
private DataSet m_dataSet;
private static DataHolder m_instance;
private DataHolder()
{
m_dataSet = ... // Fill/Create it here
}
public static DataHolder Instance
{
get
{
if (m_instance = null)
m_instance = new DataHolder();
return m_instance;
}
}
public DataSet Data
{
get { return m_dataSet; }
}
}
Then, access it using DataHolder.Instance.Data
;
Upvotes: 3
Reputation: 14580
You could try passing the dataset into the constructor of each class
var something = new Something(dataset)
Upvotes: 0