Search code examples
c#strongly-typed-dataset

Add a new row into strongly 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


Solution

  • 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 ! :)