C# – Add a new row into strongly typed DataSet

cstrongly-typed-dataset

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

Best Answer

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.

Related Topic