开发者

C# access DataSet data from another class

how I can access a DataSet and it's TablesData(s) to add/delete/edit rows from another c开发者_如何转开发lass

I have a WinForm and I added

  • DataGridView dataGridView1
  • DataSet dataSet1
  • bind them with BindingSource

all the data will be saved in an XML

all work OK, I made few test projects all work fine

but when I try to test the possibility to add data row from another class, it does not show the change on the DataGridView!!!!

so I have Form1 with dataGridView1 and dataSet1 both are public

within the other Class I did

var esf = new Form1();
           
DataRow pl = esf.dataSet1.Tables["MyItems"].NewRow();

pl["Type"]  = type;
pl["Name"] = true;

esf.dataSet1.Tables["MyItems"].Rows.Add(pl);

and if I add

esf.dataSet1.WriteXml(esf.XmlSettingsFile);

it saves the file correctly!

but it overwrites other data

I feel like I'm working with another DataSet that is the same as my Original one in the Form but I need to access the data in the original DataSet in the main Form

simply I need to have the dataSet1 as public static so I can access it and add edit data to it but when I do that, Visual Studio gives me error! in the visual View of the Form!?!

any suggestions


If I understand correctly...

  1. You start the project or whatever, and use Form1 which has a DataGridView.
  2. You then run your first set of code in another class, and add some new data.
  3. If you write the XML out, you only get the new stuff, while the original stuff on Form1 is missing?

If that is the case, then it's pretty apparent what is going on...

  1. You start the project, which creates the Form1 object.
  2. You do whatever you are doing in Form1 to fill the DataGridView
  3. You run your first block of code, and the var esf = new Form1(); line creates a NEW instance of Form1, which is different than the original instance you're trying to pull data from.
  4. Any code from the other class is just operating on the newly instantiated Form1, which is different than what you're trying to access.

My assumptions might be wrong since I obviously can't see your code, but hopefully this helps.

Edit - To solve the problem...

Again, I can only speculate as to what your existing code looks like, but you can do something like this:

Instead of trying to access the values from Form2 (or whatever the other form is), set up Form2 to have access to Form1 from the get-go:

  1. Give Form2 a public property "DataSet" or something.
  2. When instantiationg Form2 (presumably from Form1), simply do this:

    Form2 reliantForm = new Form2();

    relaintForm.DataSet = this.dataSet1;

    reliantForm.Show();

  3. Form2 now has a reference to the dataset and can manipulate it as needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜