views:

726

answers:

5

Hi, I have following XML document:

<Form ID="1">
  <Persons>
    <Person Name="Mike"/>
    <Person Name="Alan"/>
  </Persons>
</Form>

I have created the Strongly Typed DataSet file (.XSD) and the MyForm.cs file based on that .XSD file

Then, how to add a new Person to table Persons ?

I tried that code:

        Form_3 form = new Form_3();
        form.ReadXml(TextBox1.Text, XmlReadMode.Auto)
        Form3.Person newPerson= form.Person.NewPersonRow();
        newPerson.Name= "Tony";

        form.Person.Rows.Add(newPerson);

but the result is:

<Form ID="1">
  <Persons>
    <Person Name="Mike"/>
    <Person Name="Alan"/>
  </Persons>
  <Person Name="Tony"/>
</Form>

so, I tried that code:

        Form3.Person newPerson= form.Person.NewPersonRow();
        newPerson.Name= "Tony";

        form.Persons.Rows.Add(newPerson)

but this thows an exception:

  "This row already belongs to another table."

So how to resolve that problem ?

[EDIT] Here's my Form_3.XSD file schema: Click here to see

alt text

+1  A: 

Try the ImportRow method.

John Buchanan
This was my issue. Thanks!
dwaz
A: 

Hmm, it seems to be adding that new Person, a message box appears to overwrite the .xml file, but still the .xml file looks the same as it used to

Tony
+3  A: 

Assuming that Persons is a DataTable in your typed DataSet instance form, I believe what's happening is you're attempting to add a Row from one DataTable (form.Person) to a Row in another DataTable (form.Persons). You can't do this even if the two DataTables have the same schema.

To fix this problem (and to add your new record to the Persons DataTable) add change:

Form3.Person newPerson= form.Person.NewPersonRow();        
newPerson.Name= "Tony";        
form.Persons.Rows.Add(newPerson)

to:

Form3.PersonsRow newPerson = form.Persons.NewPersonsRow();
newPerson.Name = "Tony";
form.Persons.AddPersonsRow(newPerson);

EDIT - after the schema was posted

I think this will do what you need.

Form_3 form = new Form_3();
Form_3.PersonRow newPerson = form.Person.NewPersonRow();
newPerson.Person_Text = "Tony";
form.Person.AddPersonRow(newPerson);

Note that according to your schema (the screenshot at least; I didn't check your link), the Person table has no Name column. I used the Person_Text field instead.

Jay Riggs
A: 

Jay Riggs >>

As You have noticed, the Persons table doesn't have the "Name" property, so Your code won't work.

Tony
@Tony - you can reply to answers (or questions) by clicking "add comment."
Jeff Sternal
A: 

Finally ! It worked :)

I just had to insert that line:

newPerson.Form_Id = 0;

Thanks to this, the framework knows where exactly insert the newPersonRow

So, the code looks like that:

        Form3.Person newPerson= form.Person.NewPersonRow();
        newPerson.Name= "Tony";
        newPerson.Form_Id = 0;
        form.Person.Rows.Add(newPerson);

Thank You guys for Your help ! :)

Tony
@Tony, you should accept this as the answer
Nathan Koop