c# - How to create a DataTable from a DataView

DataView ToTable() method
.Net framework's DataView represents a data bindable, customized view of a DataTable for filtering, sorting, searching, editing, and navigation. DataView does not store any data, it represents a connected view of its corresponding DataTable. DataTable represents one table of in-memory data.

DataView ToTable() method has four overloaded methods, those are ToTable(), ToTable(String), ToTable(Boolean, String[]), and ToTable(String, Boolean, String[]).

DataView ToTable() method creates and returns a new DataTable based on rows in an existing DataView. This method return value type is System.Data.DataTable which represents a new DataTable instance that contains the requested rows and columns. This method returned DataTable contains the same columns as the input table. Returned DataTable name is also the same as the source DataTable.

DataView ToTable(String) overloaded method also creates and returns a DataTable based on rows in an existing DataView. The ToTable(String) method requires passing a parameter named tableName. This parameter value represents the name of the returned DataTable. This method's returned DataTable contains the same columns as the input table. But we can specify a table name of the returned DataTable.

DataView ToTable(Boolean, String[]) overloaded method has two required parameters named distinct and columnNames. The distinct parameter value data type is a Boolean. This parameter value true indicates the returned DataTable contains rows that have distinct values for all its columns. This parameter's default value is false.

ToTable(Boolean, String[]) method's 'columnNames' parameter value type is System.String[] which represents a string array that contains a list of column names to be included in the returned DataTable object. So by using this parameter we can specify whether returned DataTable contains only distinct rows and we also can specify the column names.

DataView ToTable(String, Boolean, String[]) overloaded method requires passing three parameters named tableName, distinct, and columnNames. Using this method we can specify returned DataTable's table name, and column names and whether it contains only distinct values for all its columns or not.

The following ADO.NET C# example code demonstrates to us how can we create a new DataTable based on rows in an existing DataView programmatically at run time in an ASP.NET application.
DataViewToTableMethod.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "BookID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = true;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "Category";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "BookName";
        dc3.DataType = typeof(string);

        DataColumn dc4 = new DataColumn();
        dc4.ColumnName = "Author";
        dc4.DataType = typeof(string);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3, dc4 });

        dt.Rows.Add(new object[] { 1, "iPhone", "iPhone User Interface Cookbook: RAW", "Cameron Banga" });
        dt.Rows.Add(new object[] { 2, "MySQL", "MySQL 5.1 Plugin Development", "Andrew Hutchings, Sergei Golubchik" });
        dt.Rows.Add(new object[] { 3, "MySQL", "MySQL Admin Cookbook", "Daniel Schneller, Udo Schwedt" });
        dt.AcceptChanges();

        Label1.Text = "Source DataTable";
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();

        //this line create a new DataView
        DataView dView = new DataView(dt);
        dView.RowFilter = "Category = 'MySQL'";

        Label2.Text = "Here we create a new DataView<br />" +
                      "and set the RowFilter (Category = 'MySQL')";

        GridView2.DataSource = dView;
        GridView2.DataBind();

        //this line create a new DataTable from DataView
        DataTable dt2 = dView.ToTable();

        Label3.Text = "Here we create a new DataTable from DataView";
        GridView3.DataSource = dt2;
        GridView3.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DataView ToTable method to create a new DataTable in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to use DataView ToTable method
            <br /> to create a new DataTable in ado.net
        </h2>
        <hr width="450" align="left" color="CornFlowerBlue" />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="600"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="DarkSlateBlue" Height="30" />
            <RowStyle BackColor="MediumVioletRed" />
            <AlternatingRowStyle BackColor="PaleVioletRed" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label2"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="600"
            Font-Names="Courier"
            >

            <HeaderStyle BackColor="DarkSlateBlue" Height="30" />
            <RowStyle BackColor="MediumVioletRed" />
            <AlternatingRowStyle BackColor="PaleVioletRed" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label3"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView3"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="600"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="DarkSlateBlue" Height="30" />
            <RowStyle BackColor="MediumVioletRed" />
            <AlternatingRowStyle BackColor="PaleVioletRed" />
        </asp:GridView>
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to add a new row to the DataView

Add a new row to a DataView
The DataView is a customized view of a DataTable for sorting, filtering, searching, editing, and navigation. The DataView does not store data. When the asp.net developer changes the DataView's data that will affect the DataTable. But when they change the DataTable's data that will affect all associated DataViews. The DataView is much like a database view.

The following asp.net c# tutorial code demonstrates how we can add a new row to a DataView. Here we used the DataView class AddNew() method to add a new row to a DataView instance.

The DataView class AddNew() method adds a new row to the DataView. The AddNew() method returns a new DataRowView object. The DataRowView class represents a customized view of a DataRow. After adding the row to the DataView we can insert data into the row for specified columns.

The DataRowView class EndEdit() method commits changes to the underlying DataRow and ends the editing session that was begun with BeginEdit() method. The asp.net developers can use CancelEdit() method to discard the changes made to the DataRow. Finally, the asp.net c# developers can add a new row to the DataView by using DaatView class AddNew() method and DataRowView class EndEdit() method.
DataViewAddNewMethod.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "BookID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = true;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "Category";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "BookName";
        dc3.DataType = typeof(string);

        DataColumn dc4 = new DataColumn();
        dc4.ColumnName = "Author";
        dc4.DataType = typeof(string);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3, dc4 });

        dt.Rows.Add(new object[] { 1, "Joomla", "Joomla! 1.5 JavaScript jQuery", "Jose Argudo Blanco" });
        dt.Rows.Add(new object[] { 2, "jQuery", "ASP.NET jQuery Cookbook", "Sonal Aneel Allana" });
        dt.AcceptChanges();

        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();

        //this line create a new DataView
        DataView dView = new DataView(dt);
        dView.Sort = "BookName DESC" ;

        Label1.Text = "Here we create a new DataView<br />" +
                      "and set the sort order (BookName DESC)";

        GridView2.DataSource = dView;
        GridView2.DataBind();

        DataRowView drv = dView.AddNew();
        drv["BookID"] = 3;
        drv["Category"] = "Games";
        drv["BookName"] = "Unity Game Development Essentials";
        drv["Author"] = "Will Goldstone";
        drv.EndEdit();

        Label2.Text = "Here we add a new row to the DataView, Now the DataView is...";
        GridView3.DataSource = dView;
        GridView3.DataBind();

        Label3.Text = "Now the source DataTable is...";
        GridView4.DataSource = dt;
        GridView4.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DataView AddNew Method to add a new row to the DataView in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to use DataView AddNew Method
            <br /> to add a new row to the DataView in ado.net
        </h2>
        <hr width="575" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="700"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="DarkBlue" Height="30" />
            <RowStyle BackColor="Orange" />
            <AlternatingRowStyle BackColor="DarkOrange" />
        </asp:GridView>
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="700"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="CadetBlue" Height="30" />
            <RowStyle BackColor="Orange" />
            <AlternatingRowStyle BackColor="DarkOrange" />
        </asp:GridView>
        <asp:Label
             ID="Label2"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView3"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="700"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="CadetBlue" Height="30" />
            <RowStyle BackColor="Orange" />
            <AlternatingRowStyle BackColor="DarkOrange" />
        </asp:GridView>
        <asp:Label
             ID="Label3"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView4"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="700"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="DarkBlue" Height="30" />
            <RowStyle BackColor="Orange" />
            <AlternatingRowStyle BackColor="DarkOrange" />
        </asp:GridView>
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to create a DataTable with distinct rows from a DataView

Create a DataTable with distinct rows from a DataView
The DataView is a customized view of a DataTable for sorting, filtering, searching, editing, and navigation. The DataView does not store data. When the asp.net developer changes the DataView's data that will affect the DataTable. But when they change the DataTable's data that will affect all associated DataViews. The DataView is much like a database view.

The DataTable class represents one table of in-memory data. The DataTable is a central object in the ADO.NET library. The DataSet and DataView objects use DataTable.The following asp.net c# tutorial code demonstrates how we can create a DataTable with distinct rows from a DataView. Here we used the DataView class ToTable() method’s specified overload to create a DataTable with distinct rows from a specified DataView instance.

The DataView class ToTable() method creates and returns a new DataTable based on rows in an existing DataView. In the DataView class ToTable() method’s specified overload we passed a Boolean value that indicates whether the returned DataTable contains rows that have distinct values for all its columns or not.

The default value of this parameter is false. If this parameter value is set to true then the returned DataTable contains rows that have distinct values for all its columns. We also pass the column names to this method overload to distinct the rows based on them while creating the new DataTable.

The DataView ToTable() method returns a new DataTable instance that contains the requested rows and columns.The asp.net developers can use the overloaded version of the ToTable() method when they want to retrieve distinct values in a subset of available columns, specifying a new name for the returned DataTable.
DataTableFromADataViewWithDistinctValues.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "BookID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = true;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "Category";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "BookName";
        dc3.DataType = typeof(string);

        DataColumn dc4 = new DataColumn();
        dc4.ColumnName = "Author";
        dc4.DataType = typeof(string);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3, dc4 });

        dt.Rows.Add(new object[] { 1, "Flash", "Papervision3D Essentials", "Jeff Winder, Paul Tondeur" });
        dt.Rows.Add(new object[] { 2, "JBoss", "jBPM Developer Guide", "Mauricio Salatino" });
        dt.Rows.Add(new object[] { 3, "Flash", "Flash Multiplayer Virtual Worlds", "Makzan" });
        dt.Rows.Add(new object[] { 4, "Flash", "Papervision3D Essentials", "Jeff Winder, Paul Tondeur" });
        dt.AcceptChanges();

        Label1.Text = "Source DataTable: " + dt.TableName;
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();

        //this line create a new DataView
        DataView dView = new DataView(dt);
        dView.RowFilter = "Category = 'Flash'";

        Label2.Text = "Here we create a new DataView<br />" +
                      "and set the RowFilter (Category = 'Flash')";

        GridView2.DataSource = dView;
        GridView2.DataBind();

        //this line create a new DataTable from DataView
        DataTable dt2 = dView.ToTable(false, "BookName", "Author");

        Label3.Text = "Here we create a new DataTable from DataView";

        GridView3.DataSource = dt2;
        GridView3.DataBind();

        //this line create a new DataTable from DataView with distinct values
        DataTable dt3 = dView.ToTable(true, "BookName", "Author");

        Label4.Text = "Here we create a new DataTable from DataView with distinct values";

        GridView4.DataSource = dt3;
        GridView4.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to create a new DataTable from a DataView with distinct values (rows) in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to create a new DataTable from a
            <br /> DataView with distinct values (rows) in ado.net
        </h2>
        <hr width="450" align="left" color="CornFlowerBlue" />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="750"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="HotPink" Height="30" />
            <RowStyle BackColor="OliveDrab" />
            <AlternatingRowStyle BackColor="DarkOliveGreen" />
        </asp:GridView>
        <asp:Label
             ID="Label2"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="750"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="HotPink" Height="30" />
            <RowStyle BackColor="OliveDrab" />
            <AlternatingRowStyle BackColor="DarkOliveGreen" />
        </asp:GridView>
        <asp:Label
             ID="Label3"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView3"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="750"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="HotPink" Height="30" />
            <RowStyle BackColor="OliveDrab" />
            <AlternatingRowStyle BackColor="DarkOliveGreen" />
        </asp:GridView>
        <asp:Label
             ID="Label4"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView4"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="750"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="HotPink" Height="30" />
            <RowStyle BackColor="OliveDrab" />
            <AlternatingRowStyle BackColor="DarkOliveGreen" />
        </asp:GridView>
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to sort a DataView

DataView Sort Property
.NET framework's DataView represents a data bindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation. DataView class exists in System.Data namespace.

The DataView Sort property allows us to get or set the sort column or columns and sort order for the DataView. DataView Sort property value data type is a String. This value represents a String that contains the column name followed by ASC ascending or DESC descending.

If we want to sort DataView by multiple columns, we need to separate multiple columns by commas. By default, columns are sorted in ascending order. We can implement the DataView Sort property value as "BookName Desc" for single-column sorting or "Country ASC, City DESC" for multiple columns sorting.

The following ADO.NET C# example code demonstrates to us how can we sort DataView data programmatically at run time in an ASP.NET application.
DataViewSortProperty.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "BookID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = true;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "Category";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "BookName";
        dc3.DataType = typeof(string);

        DataColumn dc4 = new DataColumn();
        dc4.ColumnName = "Author";
        dc4.DataType = typeof(string);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3, dc4 });

        dt.Rows.Add(new object[] { 1, "Java", "Google App Engine Java and GWT Application Development", "Daniel Guermeur, Amy Unruh" });
        dt.Rows.Add(new object[] { 2, ".NET", "ASP.NET MVC 1.0 Quickly", "Maarten Balliauw" });
        dt.Rows.Add(new object[] { 3, "Java", "NetBeans IDE 7 Cookbook", "Rhawi Dantas" });
        dt.AcceptChanges();

        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();

        //this line create a new DataView
        DataView dView = new DataView(dt);
        dView.Sort = "BookName DESC" ;

        Label1.Text = "Here we create a new DataView<br />" +
                      "and set the sort order (BookName DESC)";

        GridView2.DataSource = dView;
        GridView2.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DataView Sort Property in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to use DataView Sort Property in ado.net
        </h2>
        <hr width="575" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="575"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="OrangeRed" Height="30" />
            <RowStyle BackColor="DarkOrchid" />
            <AlternatingRowStyle BackColor="DarkMagenta" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="575"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="OrangeRed" Height="30" />
            <RowStyle BackColor="DarkOrchid" />
            <AlternatingRowStyle BackColor="DarkMagenta" />
        </asp:GridView>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to get the source table of a DataView

Get the source table of a DataView
The DataView is a customized view of a DataTable for sorting, filtering, searching, editing, and navigation. The DataView does not store data. When the asp.net developer changes the DataView's data that will affect the DataTable. But when they change the DataTable's data that will affect all associated DataViews. The DataView is much like a database view.

The following asp.net c# tutorial code demonstrates how we can get the source table of a DataView. Here we used the DataView class Table property to get the source DataTable object of a specified DataView instance.

The DataView class Table property gets or sets the source DataTable. The Table property value is a DataTable that provides the data for this view.

The DataTable also has a DefaultView property which returns the default DataView for the table. The asp.net developers can only set the Table property if the current value is null.

The DataTable class represents one table of in-memory data. The DataTable is a central object in the ADO.NET library. The DataSet and DataView objects use DataTable.

So finally, the asp.net c# developers can get the source table (DataTable) of a DataView instance by using the DataView class Table property.
DataViewTableProperty.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "BookID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = true;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "Category";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "BookName";
        dc3.DataType = typeof(string);

        DataColumn dc4 = new DataColumn();
        dc4.ColumnName = "Author";
        dc4.DataType = typeof(string);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3, dc4 });

        dt.Rows.Add(new object[] { 1, "Apple", "iPad 2 Pocket Guide, The", "Jeff Carlson" });
        dt.Rows.Add(new object[] { 2, "Ajax", "Head First Ajax", "Rebecca M. Riordan" });
        dt.Rows.Add(new object[] { 3, "Ajax", "Ajax: The Definitive Guide", "Anthony T. Holdener III" });
        dt.AcceptChanges();

        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();

        //this line create a new DataView
        DataView dView = new DataView(dt);
        dView.RowFilter = "Category = 'Ajax'";

        Label1.Text = "Here we create a new DataView with RowFilter expression (Category = 'Ajax')";

        GridView2.DataSource = dView;
        GridView2.DataBind();

        DataTable dViewSourceTable = dView.Table;
        Label2.Text = "Here we get the source DataTable of DataView" ;

        GridView3.DataSource = dViewSourceTable;
        GridView3.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DataView Table property to get the source DataTable in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to use DataView Table property
            <br /> to get the source DataTable in ado.net
        </h2>
        <hr width="575" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="575"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="OliveDrab" Height="30" />
            <RowStyle BackColor="LightCoral" />
            <AlternatingRowStyle BackColor="LightSalmon" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="575"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="OliveDrab" Height="30" />
            <RowStyle BackColor="LightCoral" />
            <AlternatingRowStyle BackColor="LightSalmon" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label2"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br />
        <asp:GridView 
            ID="GridView3"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="575"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="OliveDrab" Height="30" />
            <RowStyle BackColor="LightCoral" />
            <AlternatingRowStyle BackColor="LightSalmon" />
        </asp:GridView>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to filter data in a DataView

DataView RowFilter Property
.Net framework's DataView represents a data bindable, customized view of a DataTable for sorting, searching, filtering, navigation, and editing. DataView represents a connected view of its corresponding DataTable.

DataView does not stroe data. If we change the DataView data, it will affect the DataTable. If we change the DataTable's data, it will affect all associated DataViews. DataView class exists in System.Data namespace.

DataView class’s RowFilter property allows us to get or set the expression used to filter which rows are viewed in the DataView. RowFilter property value data type is String which represents a String that specifies how rows are to be filtered.

We can assign a RowFilter value as "FirstName = 'Innee'" where 'FirstName' is a column name followed by an operator (=) and a value 'Innee' to filter on. The value must be in quotation marks.

The following ado.net c# example code demonstrates to us how can we filter a DataView's rows to display programmatically in an asp.net application.
DataViewRowFilterProperty.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "BookID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = true;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "Category";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "BookName";
        dc3.DataType = typeof(string);

        DataColumn dc4 = new DataColumn();
        dc4.ColumnName = "Author";
        dc4.DataType = typeof(string);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3, dc4 });

        dt.Rows.Add(new object[] { 1, "Flash", "Flash Multiplayer Virtual Worlds", "Makzan" });
        dt.Rows.Add(new object[] { 2, ".NET", "Entity Framework Tutorial", "Joydip Kanjilal" });
        dt.Rows.Add(new object[] { 3, "Flash", "WordPress and Flash 10x Cookbook", "Peter Spannagle, Sarah Soward" });
        dt.AcceptChanges();

        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();

        //this line create a new DataView
        DataView dView = new DataView(dt);
        dView.RowFilter = "Category = 'Flash'";

        Label1.Text = "Here we create a new DataView<br />" +
                      "and set the RowFilter expression (Category = 'Flash')";

        GridView2.DataSource = dView;
        GridView2.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DataView RowFilter Property in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to use DataView RowFilter Property in ado.net
        </h2>
        <hr width="575" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="575"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="Crimson" Height="35" />
            <RowStyle BackColor="MediumSeaGreen" />
            <AlternatingRowStyle BackColor="DarkGreen" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="575"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="Crimson" Height="35" />
            <RowStyle BackColor="MediumSeaGreen" />
            <AlternatingRowStyle BackColor="DarkGreen" />
        </asp:GridView>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to count rows in a DataView

DataView Count Property
.NET framework's DataView represents a data bindable, customized view of a DataTable for sorting, searching, filtering, navigation, and editing. The DataView object does not store data but it represents a connected view of its corresponding DataTable.

DataView RowFilter property allows us to get or set the expression used to filter which rows are viewed in the DataTable. DataView RowStateFilter property allows us to get or set the row state filter used in the DataView.

The DataView Count property allows us to get the number of records (rows) in a DataTable after RowFilter and RowStateFilter have been applied. The Count property value data type is an Int32. This integer value represents the number of records in the DataView. The Count property implements as ICollection.Count.

The following ADO.NET C# example code demonstrates to us how can we count a DataView's rows (records) programmatically at run time in an ASP.NET application.
DataViewCountProperty.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "BookID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = true;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "Category";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "BookName";
        dc3.DataType = typeof(string);

        DataColumn dc4 = new DataColumn();
        dc4.ColumnName = "Author";
        dc4.DataType = typeof(string);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3, dc4 });

        dt.Rows.Add(new object[] { 1, ".NET", "ASP.NET jQuery Cookbook", "Sonal Aneel Allana" });
        dt.Rows.Add(new object[] { 2, "Flash", "Joomla! with Flash", "Suhreed Sarkar" });
        dt.Rows.Add(new object[] { 3, ".NET", "ASP.NET 3.5 Application Architecture and Design", "Vivek Thakur" });
        dt.AcceptChanges();

        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();

        //this line create a new DataView
        DataView dView = new DataView(dt);
        dView.RowFilter = "Category = '.NET'";

        Label1.Text = "Here we create a new DataView<br />" +
                      "and set the RowFilter expression (Category = '.NET')";

        int totalRows = dView.Count;
        Label1.Text += "<br /><br />Total Rows in this DataView: " + totalRows.ToString();
        GridView2.DataSource = dView;
        GridView2.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DataView Count property to get number of records (rows) after RowFilter in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to use DataView Count property to get
            <br /> number of records (rows) after RowFilter in ado.net
        </h2>
        <hr width="575" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="575"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="DarkOrange" Height="30" />
            <RowStyle BackColor="BlueViolet" />
            <AlternatingRowStyle BackColor="Violet" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="575"
            Font-Names="Courier"
            >
            <HeaderStyle BackColor="DarkOrange" Height="30" />
            <RowStyle BackColor="BlueViolet" />
            <AlternatingRowStyle BackColor="Violet" />
        </asp:GridView>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to create a DataView

Create a new DataView
The DataView is a customized view of a DataTable for sorting, filtering, searching, editing, and navigation. The DataView does not store data. When the asp.net developer changes the DataView's data that will affect the DataTable. But when they change the DataTable's data that will affect all associated DataViews. The DataView is much like a database view.

The following asp.net c# tutorial code demonstrates how we can create a new DataView. Here we used the DataView class DataView(DataTable) constructor to create a new instance of the DataView object.

The DataView class DataView(DataTable) constructor initializes a new instance of the DataView class with the specified DataTable. The DataView (System.Data.DataTable? table) constructor has a parameter named table. The table parameter is a DataTable to add to the DataView.

The DataTable class represents one table of in-memory data. The DataTable is a central object in the ADO.NET library. The DataSet and DataView objects use DataTable.

So finally, the asp.net c# developers can create a new instance of a DataView object by using its various constructors. In the below example code, we used the DataView class DataView(DataTable) constructor to create a DataView from a specified DataTable instance.
HowToCreateADataView.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "BookID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = false;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "BookName";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "Author";
        dc3.DataType = typeof(string);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3 });

        dt.Rows.Add(new object[] { 1, "MySQL for Python", "Albert Lukaszewski, PhD" });
        dt.Rows.Add(new object[] { 2, "Python 2.6 Graphics Cookbook", "Mike Ohlson de Fine " });
        dt.Rows.Add(new object[] { 3, "Flash Game Development by Example", "Emanuele Feronato" });
        dt.AcceptChanges();

        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();

        //this line create a new DataView
        DataView dView = new DataView(dt);
        dView.Sort = "BookName DESC";

        Label1.Text = "Here we create a new DataView<br />" +
                      "and sorted it DESC by 'BookName' column";

        GridView2.DataSource = dView;
        GridView2.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to create a DataView in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to create a DataView in ado.net
        </h2>
        <hr width="450" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="525"
            >
            <HeaderStyle BackColor="PaleVioletRed" />
            <RowStyle BackColor="SeaGreen" />
            <AlternatingRowStyle BackColor="DarkGreen" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="525"
            ShowHeaderWhenEmpty="true"
            >
            <HeaderStyle BackColor="PaleVioletRed" />
            <RowStyle BackColor="SeaGreen" />
            <AlternatingRowStyle BackColor="DarkGreen" />
        </asp:GridView>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to merge two DataTables

DataTable Merge() Method
.NET framework's DataTable represents one table of in-memory data. DataTable is a central object in the ado.net library. DataSet and DataView both objects use DataTable.

The DataTable Merge() method allows us to merge the specified DataTable with the current DataTable. The Merge() method is used to merge two DataTable objects that have largely similar schemas. Child tables are not affected or merged with the current table. If a table has child tables as part of the relationship, each child table must be merged individually.

DataTable Merge method is overloaded, those are Merge(DataTable), Merge(DataTable, Boolean), and Merge(DataTable, Boolean, MissingSchemaAction).

DataTable Merge(DataTable) overloaded method allows us to merge the specified DataTable with the current DataTable. Merge(DataTable) requires passing a parameter named table. This table parameter value type is System.Data.DataTable which represents the DataTable to be merged with the current DataTable. This method allows a client application to have a refreshed DataTable with the latest data from the data source.

DataTable Merge(DataTable, Boolean) overloaded method allows us to merge the specified DataTable with the current DataTable, including whether to preserve changes in the current DataTable.

Merge(DataTable, Boolean) method requires passing two parameters named 'table' and 'preserveChanges'. this 'preserveChanges' parameter value data type is a Boolean. If we set this parameter value to true, it preserves changes in the current DataTable. The false value does not preserve changes. The preserveChanges parameter value true means, incoming values do not overwrite existing values in the current row version of the existing row.

DataTable Merge(DataTable, Boolean, MissingSchemaAction) overloaded method allows us to merge the specified DataTable with the current DataTable, including whether to preserve changes and how to handle missing schema in the current DataTable.

Merge(DataTable, Boolean, MissingSchemaAction) method has three required parameters named table, preserveChanges, and missingSchemaAction. This missingSchemaAction parameter value type is System.Data.MissingSchemaAction which represents one of the MissiingScemaAction values. MissingSchemaAction enumeration values are Add, AddWithKey, Error, and Ignore.

The following ADO.NET C# example code demonstrates to us how can we merge a specified DataTable with the current DataTable programmatically at run time in an ASP.NET application.
DataTableMergeMethod.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "BookID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = false;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "BookName";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "Author";
        dc3.DataType = typeof(string);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3 });

        dt.Rows.Add(new object[] { 1, "Drupal 6 Social Networking", "Michael Peacock" });
        dt.Rows.Add(new object[] { 2, "Drupal 6 Site Builder Solutions", "Mark Noble" });
        dt.AcceptChanges();

        Label1.Text = "This is 'Books' DataTable with 2 rows";

        GridView1.DataSource = dt;
        GridView1.DataBind();

        DataTable dt2 = dt.Clone();
        dt.TableName = "NewBooks";
        dt2.Rows.Add(new object[] { 1, "Flash with Drupal", "Travis Tidwell" });

        Label2.Text = "This is 'NewBooks' DataTable, clone of 'Books' DataTable";
        Label2.Text += "<br />Here we insert a new row";

        GridView2.DataSource = dt2;
        GridView2.DataBind();

        //this line merge dt2 with dt
        dt.Merge(dt2);

        Label3.Text = "Here we merge 'NewBooks' DataTable with 'Books' DataTable";
        GridView3.DataSource = dt;
        GridView3.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DataTable Merge Method in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to use DataTable Merge Method in ado.net
        </h2>
        <hr width="525" align="left" color="CornFlowerBlue" />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="525"
            >
            <HeaderStyle BackColor="DarkOrchid" />
            <RowStyle BackColor="Tan" />
            <AlternatingRowStyle BackColor="BurlyWood" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label2"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="525"
            >
            <HeaderStyle BackColor="DarkOrchid" />
            <RowStyle BackColor="Tan" />
            <AlternatingRowStyle BackColor="BurlyWood" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label3"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br />
        <asp:GridView 
            ID="GridView3"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="525"
            >
            <HeaderStyle BackColor="DarkOrchid" />
            <RowStyle BackColor="Tan" />
            <AlternatingRowStyle BackColor="BurlyWood" />
        </asp:GridView>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to use DataTable Compute method

DataTable Compute() Method
.NET framework's DataTable represents one table of in-memory data. The DataTable class exists in the System.Data namespace.

DataTable Compute() method allows us to compute the given expression on the current rows that pass the filter criteria. DataTable Compute() method requires passing two parameters named expression and filter.

Both parameters value data type are String. The expression parameter represents the expression to compute and the filter parameter represents the filter to limit the rows that evaluate in the expression.

DataTable Compute() method return value type is Object which represents an Object, set to the result of the computation. Compute() method return DBNull.Value, if the expression evaluates to null.

We can pass the expression parameter value as:
"Count(BookName)" where 'BookName' is a column name.
"Sum(Quantity * BookPrice)" where 'Quantity' and 'BookPrice' are column names.

We can pass the filter parameter value as "CategoryID = 5" where 'CategoryID' is a column name.

The following ADO.NET C# example code demonstrates to us how can we apply DataTable Compute method in an ASP.NET application.
DataTableComputeMethod.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "CategoryID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = false;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "BookName";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "Author";
        dc3.DataType = typeof(string);

        DataColumn dc4 = new DataColumn();
        dc4.ColumnName = "Price";
        dc4.DataType = typeof(decimal);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3,dc4 });

        dt.Rows.Add(new object[] { 1, "asp.net example ebook", "Jones",75 });
        dt.Rows.Add(new object[] { 2, "coldfusion example ebook", "Jenny", 45 });
        dt.Rows.Add(new object[] { 2, "flex example ebook", "Anne", 65 });

        dt.AcceptChanges();

        GridView1.DataSource = dt;
        GridView1.DataBind();

        string totalPrice = dt.Compute("Sum(Price)", "CategoryID = 2").ToString();
        Label1.Text ="Total Price (CategoryID=2): " + totalPrice.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DataTable Compute Method in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to use DataTable Compute Method in ado.net
        </h2>
        <hr width="525" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="525"
            >
            <HeaderStyle BackColor="OrangeRed" />
            <RowStyle BackColor="Tan" />
            <AlternatingRowStyle BackColor="BurlyWood" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to copy a DataTable

Copy a DataTable
The DataTable class represents one table of in-memory data. The DataTable objects are conditionally case-sensitive. To create a DataTable programmatically the asp.net developers must first define its schema by adding DataColumn objects to the DataColumnCollection. To add rows to a DataTable, the developers must use the NewRow() method to return a new DataRow object at first. The DataTable also contains a collection of Constraint objects that can be used to ensure the integrity of the data.

The following asp.net c# tutorial code demonstrates how we can copy a DataTable. Here we used the DataTable class Copy() method to copy a DataTable instance.

The DataTable class Copy() method copies both the structure and data for this DataTable. The Copy() method returns a new DataTable. This method returns a new DataTable with the same structure and data as this DataTable.

The DataTable Copy() method creates a new DataTable with the same structure and data as the original DataTable. To copy the structure to a new DataTable without data the asp.net web developers have to use Clone() method.
ComboBoxChangeDataSource.aspx

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html>
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.TableName = "Books";

        DataColumn dc1 = new DataColumn();
        dc1.ColumnName = "BookID";
        dc1.DataType = typeof(int);
        dc1.AllowDBNull = false;
        dc1.Unique = true;

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "BookName";
        dc2.DataType = typeof(string);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "Author";
        dc3.DataType = typeof(string);

        dt.Columns.AddRange(new DataColumn[] { dc1, dc2, dc3 });

        dt.Rows.Add(new object[] { 1, "WordPress 2.8 Theme Design", "Tessa Blakeley Silver" });
        dt.Rows.Add(new object[] { 2, "WordPress and Flash 10x Cookbook", "Peter Spannagle, Sarah Soward" });

        dt.AcceptChanges();

        GridView1.DataSource = dt;
        GridView1.DataBind();

        DataTable myCopyDataTable;
        //this line make a copy of 'Books' DataTable
        myCopyDataTable = dt.Copy();
        myCopyDataTable.TableName = "AllBooks";

        myCopyDataTable.Rows.Add(new object[] { 3, "WordPress 3 Search Engine Optimization", "Michael David" });
        //uncomment that line to get an error message because
        //Clone DataTable keeps original DataTable schemas and constraints
        //myCopyDataTable.Rows.Add(new object[] { 3, "WordPress 3 Search Engine Optimization", "Michael David" });

        myCopyDataTable.AcceptChanges();

        Label1.Text = "Copy of the DataTable. Using DataTable.Copy Method";
        Label1.Text += "<br />After copy we insert a new row<br />";

        GridView2.DataSource = myCopyDataTable;
        GridView2.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to copy both structure and data from one DataTable to another DataTable in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to copy both structure and data from
            <br /> one DataTable to another DataTable in ado.net
        </h2>
        <hr width="525" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="525"
            >
            <HeaderStyle BackColor="DarkOrchid" />
            <RowStyle BackColor="OrangeRed" />
            <AlternatingRowStyle BackColor="DeepPink" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="DodgerBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="525"
            ShowHeaderWhenEmpty="true"
            >
            <HeaderStyle BackColor="DarkOrchid" />
            <RowStyle BackColor="OrangeRed" />
            <AlternatingRowStyle BackColor="DeepPink" />
        </asp:GridView>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>