When to Use Methods Clone() ,Copy(), AcceptChanges() in ADO.NET
Today i want to discuss in detail how to work with Clone ,Copy and Acceptchanges of these three methods for a Dataset. In which scenario these methods will work i will illustrate with detail description and code snippets using C#.
Today i want to discuss in detail how to work with Clone and Copy of these two methods for Datatable. How to work with these methods in a Datatable. In which scenario these methods will work i will illustrate with detail description in asp.net using C#.
In Some Scenarios you will have to Copy the Rows in a new Datatable . ADO.NET provides an excellent way and easiest way to copy the rows in a new Datatable For ex : if you want to eliminate duplicate rows of a original datatable and bind it to some Control( Ex . DataGrid, Chart , and other .Net Controls) or from example you want to copy the rows from dataset into a datatable.
DataNew dtnew = new Datatable();
dtOriginal = dtOld.Copy(); // Assuming that dtOld had some Records
for(int Icolumn =0 ; Icolumn <= dtNew.Columns.Count; )
{
for(int i=0;i< upto rowsCount ; increament )
{
for(int j=0; j< increament upto rows count ; increament)
{
if(DtNew.Rows[i][Icolumn].ToString() == dtOld.Rows[j][Icolumn].ToString())
{
DtNew..Rows[j].Delete();
DtNew.AcceptChanges();
Icolumn ++;
}
}
}
GridExcel.DataSource = DtNew;
GrdExcel.DataBind();
Simple One to Copy the rows in a dataset...
Changes
DataTable dtable=new DataTable();
dtable=ds.Tables[0].copy();
When you Update/Delete the rows of a datatable you need to see the changes reflected on datatable and save those values then you can call AcceptChanges() method. Datatable.Clone
The Schema (Column names) of the Old Datatable will be Copied in to New Datatable
DataTable dt=new DataTable();
dt=ds.Table[0].clone(); // columns are Copied in the Old Datatable....
Note : You can use these in Array type of Declarations....
Note : Code Snippets gives a brief Idea it may not reflect the Original Code Certain Changes with existing code (i.e. given above) can yield a Fruitful result.
Hi Srirama.
Nice article.
Let me included few points.
1.Copy and the Clone methods create a new DataTable with the same structure as the
original DataTable.
2.The DataTable created by the Copy method will have same DataRows as the original table.
But by using the Clone method DataTable does not contain any DataRows.
3.Clone method creates a DataTable
with same structure and constraints but without
data.
4.Copy method creates DataTable with same structure but it contains the data also.
Regards
Sridhar.
DNS Member.
"Hope for the best.. Prepare for the worst.."