coder
coder

Reputation: 2000

update datatable inside a dataset

I want to know how to update a Datatable which is inside a dataset.I have a datatable in which i have details of some item.Now i want to add this into a dataset for some purpose and update it.Give me some suggesions to solve this..

this is my code:

                DataRow dr;
                dr = Basket_DataTable.NewRow();
                Basket_DataTable.Rows.Add(dr);
                dr["PId"] = getPId.ToString();
                dr["ProductName"] = getProductName.ToString();
                dr["ImagePath"] = getImagePath.ToString();
                dr["ProductPrice"] = getProductPrice.ToString();
                dr["Quantity"] = getQuantity.ToString();
                dr["ProductDescription"] = getProductDescription.ToString();
                dr["TotalPrice"] = getProductPrice.ToString();
                Basket_DataTable.AcceptChanges();

Basket_DataTable is my datatable which i need to add to a dataset and update..

Upvotes: 1

Views: 9519

Answers (2)

Habib
Habib

Reputation: 223247

I believe you want to add new Rows to your existing DataTable in your DataSet. Instead of creating a new DataTable, your Basket_DataTable should refer to your data table in the data set.

Something like.

//Create new Row from your DataTable in DataSet
DataRow dr = yourDataSet.Tables["Basket_DataTable"].NewRow();
// here you can refer to your datatable with the index as well 
//e.g. yourDataSet.Tables[0]

Basket_DataTable.Rows.Add(dr);
dr["PId"] = getPId.ToString();
dr["ProductName"] = getProductName.ToString();
dr["ImagePath"] = getImagePath.ToString();
dr["ProductPrice"] = getProductPrice.ToString();
dr["Quantity"] = getQuantity.ToString();
dr["ProductDescription"] = getProductDescription.ToString();
dr["TotalPrice"] = getProductPrice.ToString();

//Remember to add your row to the table. 
yourDataSet.Tables["Basket_DataTable"].Rows.Add(dr);

In your current code you are not adding the new row to the datatable. Remember to include the row in the datatable.

Upvotes: 2

Rhumborl
Rhumborl

Reputation: 16609

If the DataTable is already in an existing DataSet, but you want to add it to another one, you need to create a copy first - A DataTable instance can only have one parent DataSet.

DataTable Basket_DataTable_copy = Basket_DataTable.Copy();
yourDataSet.Tables.Add(Basket_DataTable_copy);

Then you can do your updates on Basket_DataTable_copy

see DataTable.Copy on MSDN

Upvotes: 0

Related Questions