"DataTable already belongs to another DataSet"

Viewed 25827

I can't figure out why I am getting a "DataTable already belongs to another DataSet" exception.

Here is my code:

DataSet AlertSet = new DataSet();

DataTable generalAlertData = new DataTable("GeneralAlertData");
generalAlertData = //function that returns datatable

//throws exception
AlertSet.Tables.Add(generalAlertData)

When is another dataset being created and when is the generalAlertData datatable being added to it?

I tried using a slightly different syntax to create and add the table and got the same error:

DataSet AlertSet = new DataSet();

DataTable generalAlertData = //function that returns datatable

//throws exception
AlertSet .Tables.Add(generalAlertData);
4 Answers

It depends on what your function that retrieve the datatable does.
If that function use a DataAdapter and fills a dataset then you have the DataSet property of the table automatically assigned and you need to remove it before assigning a different DataSet

You could try this to remove the original DataSet and use your own

    DataTable generalAlertData = GetTable();
    DataSet u = generalAlertData.DataSet;
    u.Tables.Remove(generalAlertData.TableName);
    AlertSet.Tables.Add(generalAlertData);

So, if your hypothetical GetTable works in this way

public DataTable GetTable()
{
    ...
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    return ds.Tables[0];
}

then you have the DataSet assigned to the returned datatable.
Instead this code doesn't assign anything to the DataSet property

public DataTable GetTable()
{
    ...
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    return dt;
}

The DataTable returned from the method call, was added to a DataSet. Make sure it's not added to a DataSet; just build a stand alone DataTable.

As a side-note, returning a DataTable from a method call that assigns to this one makes the line above it irrelevant (the new).

Related