DataView.ToTable() method in ADO.Net 2.0
It creates and returns a new DataTable based on rows in
an existing DataView. With this method ADO.Net 2.0 prevents the above difficulty
by exposing 4 overloads.
Overloads
DataView.ToTable ()
Creates and returns a new DataTable based on rows in an
existing DataView.
DataView.ToTable (String)
Creates and returns a new DataTable based on rows in an
existing DataView with a string table name as argument.
DataView.ToTable (Boolean, String[])
Creates and returns a new DataTable based on rows in an
existing DataView. If the Boolean is true, the returned System.Data.DataTable
contains rows that have distinct values for all its columns. The default value
is false. The string array will take the column name list and will output the
datable with the same columns and in the same order specified in the
argument.
DataView.ToTable (String, Boolean, String[])
Creates and returns a new DataTable based on rows in an
existing DataView. The string array will take the column name list and will
output the datable with the same columns and in the same order specified in the
argument.
Implementation
The above requirement is now can be done with the
ToTable() method with very less effort.
DataTable dt = new DataTable();
DataRow dr ;
DataColumn dc1 = new DataColumn();
dc1.ColumnName ="Name";
dt.Columns.Add(dc1);
dr= dt.NewRow();
dr[0] = "Satheesh";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "Vadivel";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "naveen";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "viru";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "mithun";
dt.Rows.Add(dr);
DataView dvSort = dt.DefaultView;
dvSort.Sort = "Name";
DataTable dtSorted = dvSort.ToTable();
DataTableReader dtdr =
dtSorted.CreateDataReader();
while (dtdr.Read())
{
Response.Write(dtdr[0].ToString()+"<br>");
}
//Copy one dt to another
DataTable finaldt = new DataTable();
finaldt.Load(dtSorted.CreateDataReader());
dtdr = finaldt.CreateDataReader();
while (dtdr.Read())
{
Response.Write(dtdr[0].ToString() +
"<br>");
}
|