开发者

Add a new row into strongly typed DataSet?

开发者 https://www.devze.com 2022-12-13 16:25 出处:网络
I have following XML document: <Form ID=\"1\"> <Persons> <Person Name=\"Mike\"/> <Person Name=\"Alan\"/>

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 exce开发者_JS百科ption:

  "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

Add a new row into strongly typed DataSet?


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.


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


Try the ImportRow method.

0

精彩评论

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