Table in dataset has been cleared too when clear a different table - c#

I assigned a table data in dataset to a new table. When I clear the new table(dt), table(ds.Tables[0]) in dataset has been cleared too, why? And how to avoid it to be cleared too?
DataTable dt = new DataTable();
DataSet ds = new DataSet();
\\some code to assign data to ds
below code will execute when a button is clicked, first click works well,second click caused table[0] in ds empty
dt.Clear()
dt = ds.Tables[0];

Change:
dt = ds.Tables[0];
to:
dt = ds.Tables[0].Copy();
This way, dt will hold a copy of dt.Tables[0], rather than a reference to the same underlying DataTable

Related

Adding datatable to dataset creates 2 identical tables in dataset, is there another way to add?

Just an FYI, I know there are different ways to handle this, but I need it to work in this particular way for my project.
I create a DataSet(DS) and a DataTable(DT) from a DataSet I created with the DataSetGenerator in VS2010, I then add a row to the DT with some data. I then try to add the DT (which contains data in a row) to the DS. At this point in Visual Studio when I step into the next line of code, the DataSet Visualizer shows I have a DataSet with 2 identically named tables, HOWEVER, one of them has data and the other does not. This is probably an oversight on my behalf but I can't identify it. Still learning C# here so that doesn't help either. Thanks for any help!
OLD CODE
private string getStorageKey(string strStorageAccount)
{
DataSetStorageKeyDetails ds = new DataSetStorageKeyDetails();
DataSetStorageKeyDetails.StorageKeyDetailsDataTable dt = new DataSetStorageKeyDetails.StorageKeyDetailsDataTable();
string strStorageKey = "";
dt.Rows.Add(strStorageAccount);
ds.Tables.Add(dt);
DataSet dsOut = ServiceEnclosed.InterfaceService("GetStorageKey", ds);
DataTable dtr = dsOut.Tables[0];
DataSetStorageKeyDetails.StorageKeyDetailsRow dr = dt.First();
strStorageKey = dr.StorageName;
return strStorageKey;
}
NEW CODE
private string getStorageKey(string strStorageAccount)
{
DataSetStorageKeyDetails ds = new DataSetStorageKeyDetails();
string strStorageKey = "";
ds.StorageKeyDetails.Rows.Add(strStorageAccount);
DataSet dsOut = ServiceEnclosed.InterfaceService("GetStorageKey", ds);
DataTable dtr = new DataTable();
dtr = dsOut.Tables[0];
strStorageKey = dtr.Rows[0]["StorageKey"].ToString();
return strStorageKey;
}
When you create a DataSet with the DataSetGenerator, the tables you specify are automatically created when the DataSet is created. You don't have to add a new table, just access the one it already has.
private string getStorageKey(string strStorageAccount)
{
DataSetStorageKeyDetails ds = new DataSetStorageKeyDetails();
string strStorageKey = "";
ds.StorageKeyDetails.Rows.Add(strStorageAccount);
DataSet dsOut = ServiceEnclosed.InterfaceService("GetStorageKey", ds);
DataTable dtr = dsOut.Tables[0];
strStorageKey = ds.StorageKeyDetails.Rows[0].StorageName;
return strStorageKey;
}
Untested code, but I think it points you to te right direction.

"DataTable already belongs to another DataSet"

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);
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).
This is an old question now but maybe this answer will help others.
I too received this error. I looked through my source code, found literally no other datasets and was puzzled as to why this was happening.
The solution to my issue was in my data access library. It didn't have a "getDataTable" routine but I did have a getDataset routine. When I needed just a datatable I called getDataset and took the tables(0) datatable instance.
The end result of this is that I got back my datatable like I wanted, but the datatable was already part of the dataset returned from my data access call. Thus, the error.
I had to add a getDatatable routine into my data access library to eliminate this problem.
I had the same problem and I solved it using Remove. In my opinion, your code could be this:
DataSet AlertSet = new DataSet();
DataTable generalAlertData = new DataTable("GeneralAlertData");
AlertSet.Tables.Add(generalAlertData);
AlertSet.Tables.Remove(generalAlertData);
Please, let me know if this code works.
My working code was like this:
DataTable myTable = new DataTable();
private void Save()
{
DataSet myDataSet = new DataSet();
myDataSet.Tables.Add(myTable);
myDataSet.Tables.Remove(myTable);//This works
myDataSet.WriteXml("myTable.xml");
}
private void buttonSave_Click(object sender, EventArgs e)
{
Save();
}
Every time I clicked the button buttonSave, the message “DataTable already belongs to another DataSet" appeared. After writing the line code myDataSet.Tables.Remove(myTable);//This works the application started running without problems and now I can click the button more times, without losing the value of myTable and without the error message.
I hope this can help.

Copy Specific Dataset Columns to Datatable

i have a DataSet which reads xml data and it has almost 20 columns,
i need 5 columns from the DataSet .
i have tried at my level but not able to get the DataTable with the specific columns i need.
some codes which i tried are :
DataTable dt = new DataTable(); //dt is blank DataTable
DataSet ds = new DataSet(); //ds is existing DataSet which has single table in it
dt.Columns[0]=dst4.Tables[0].Columns[0];
dt.Columns.Add(dst4.Tables[0].Columns[0]);
ds.Tables.Add(dt)
dst4.Tables.Columns.Add(dt);
You could clone the table which creates an empty table with the same columns, then you can remove the redundant columns.Here is an example with named columns, you could also use the indices:
DataTable dt = ds.Tables[0].Clone();
var colToTake = new[] { "Col1", "Col3", "Col7", "Col15", "Col19" };
var colsToRemove = dt.Columns.Cast<DataColumn>()
.Where(c => !colToTake.Contains(c.ColumnName));
foreach (DataColumn colToRemove in colsToRemove)
dt.Columns.Remove(colToRemove);
say you have to copy columns "ColumnName1", "ColumnName2", "ColumnName3", "ColumnName4", "ColumnName5" to new DataTable
DataTable source = dst4.Tables[0];
DataTable dt = source.DefaultView.ToTable(false, "ColumnName1", "ColumnName2", "ColumnName3", "ColumnName4", "ColumnName5");

Extracting Data From DataGridView and Populating in XML

what i am trying to do is write a sepprate function that is in the business logic of my Windows form application. this function recieves the xml file path and the datagridview object as arguments.
This is supposed to work:
DataTable dt = new DataTable();
dt = (DataTable)datagridview.DataSource;
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml(xml_file, System.Data.XmlWriteMode.IgnoreSchema);
But i have a error everytime with the line:
dt = (DataTable)datagridview.DataSource;
[System.InvalidCastException] = {"Unable to cast object of type 'System.Windows.Forms.BindingSource' to type 'System.Data.DataTable'."}
so i was advised in another blog to try this:
BindingSource bs = (BindingSource)dgv.DataSource;
dt = (DataTable)bs.DataSource;
but i get
[System.InvalidCastException] = {"Unable to cast object of type 'ExportDataTestApp.NorthwindDataSet' to type 'System.Data.DataTable'."}
i have searched and tryed everything i would not be supprised if it is something simple as i am new to c# but i need help please
You're almost there.
BindingSource bs = (BindingSource)dgv.DataSource;
DataSet ds = (DataSet)bs.DataSource;
DataTable dt = ds.Tables["Customers"]; // or Tables[0]
Apparently you are binding with DataSourse=myDataSet, DataMember="Tablename"

How to get an underlying DataTable from a control (i.e. under DataGridView)?

dataGridView1.DataSource = myDataSet1;
dataGridView1.DataMember = "SomeTable";
And now I want to get the refference to DataTable back from my dataGridView1.
Something like this:
DataTable dt = (DataTable)dataGridView1.DataSource... ;
I'm aware of BindingContext, but couldn't find the way to get DataTable refference back.
Got it.
DataSet dataSet = (DataSet)dataGridView1.DataSource;
string tableName = dataGridView1.DataMember;
DataTable dt =dataSet.Tables[tableName];
you are assigning Dataset as datasource to your gridview. So, the line below would help u.
DataTable dt = ((DataSet)dataGridView1.DataSource).Tables[index];
Assuming that you have only one datatable in your dataset. you can also use your table name instead of index.
You can convert it in this way
BindingSource bs = (BindingSource )dgrid.DataSource;
DataTable tCxC = (DataTable ) bs.DataSource
Look at this question How can I export a GridView.DataSource to a datatable or dataset?
You can either be resilient (to avoid null error) or take a chance.
The short version is:
DataTable dt = ((DataSet) dataGridView1.DataSource).Tables[0];
A more resilient approach (not assuming the view is bound to a DataSet):
DataSet ds = dataGridView1 as DataSet;
if (ds != null) DataTable dt = ds.Tables[0];
Obviously you can inspect/check the number of tables in the DataSet.

Categories

Resources