[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 783
  • Last Modified:

"DataTable already belongs to this DataSet.

HI,

when I add records to a datatable, I get the following error.

{"DataTable already belongs to this DataSet."}

code
 da.Fill(ds);
            //dt = ds.Tables[0];

            DataTable dt;
            dt = new DataTable("Sample");
            dt.Columns.Add("Id", typeof(integer));
            dt.Columns.Add("FName", typeof(string));
            dt.Columns.Add("LName", typeof(string));

            DataRow newDataRow;

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                newDataRow = dt.NewRow();
                newDataRow["Id"] = dr["Id"].ToString();
                newDataRow["FName"] = dr["FName"].ToString();
                newDataRow["LName"] = dr["LName"].ToString();
                dt.AcceptChanges();
                Tables.Add(dt); <--- error here
            }

How can I fix the problem?

please help.

ayha
0
ayha1999
Asked:
ayha1999
1 Solution
 
AndyAinscowCommented:
Take this line:
Tables.Add(dt); <--- error here
out of the foreach loop.
If you read the error message you shoiuld notice it is telling you the table is being added more than once
0
 
ayha1999Author Commented:
Thank you so much.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now