c# - How to use DataTable AcceptChanges() method

Using DataTable AcceptChanges() Method
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 use the DataTable class AcceptChanges() method in an asp.net web application.

The DataTable class AcceptChanges() method commits all the changes made to this table since the last time AcceptChanges() method was called. So the developers use the AcceptChanges() method to commit the changes they made on a DataTable instance.

When the asp.net web developers called the AcceptChanges() method then any DataRow object still in edit mode successfully ends its edits. The DataRowState also changes. All Added and Modified rows become Unchanged, and Deleted rows are removed.

The AcceptChanges() method is generally called on a DataTable after the asp.net web developers attempt to update the DataSet using the DbDataAdapter class Update() method.
DataTableAcceptChangesMethod.aspx

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

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

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

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

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

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

        Label1.Text = "We make a blank table without any DataRow";
        GridView1.DataSource = dt;
        GridView1.DataBind();

        dt.Rows.Add(new object[] { 1, "digital camera", "225" });
        dt.Rows.Add(new object[] { 2, "calculator", "50" });

        //this line commits all the changes made to this table
        //since last time AcceptChanges() method was called
        dt.AcceptChanges();

        Label2.Text = "Now we insert some data and accept the changes";
        GridView2.DataSource = dt;
        GridView2.DataBind();

        Label3.Text = "Now we made some changes";
        //this ine update a row data
        dt.Rows[0]["ProductName"] = "television";
        //this ine update another one row data
        dt.Rows[1]["Price"] =75.25;

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

        Label4.Text = "Now we reject the new changes";
        dt.RejectChanges();
        GridView4.DataSource = dt;
        GridView4.DataBind();
    }
</script>

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

c# - How to set all the values for a DataRow through an array

DataRow ItemArray Property
.NET framework's DataRow class represents a row of data in a DataTable. DataRow class exists in the System.Data namespace.

DataRow class’s ItemArray property allows us to get or set all the values for this row through an Array. ItemArray property value type is System.Object[] which represents an Array of type Object.

If we use the ItemArray property to set a row value, the Array must have the same size and order as the DataTable's column collection. Passing null in ItemArray indicates that no value was specified.

DataRow ItemArray property throws an ArgumentException exception if the Array is larger than the table columns number. It throws InvalidCastException if a value in the Array does not match its DataType in its respective DataColumn. The property throws ConstraintException if an edit broke a constraint.

It throws ReadOnlyException if an edit tried to change the value of a read-only column. ItemArray property also throws NoNullAllowedException and DeletedRowInaccessibleException. Developers can generate exceptions in the ColumnChanging event or RowChanging event.

The following ADO.NET C# example code demonstrates to us how can we use the DataRow ItemArray property in an ASP.NET application.
DataRowItemArrayProperty.aspx

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

<!DOCTYPE html>
<script runat="server">
    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, "Network Your Computers & Devices Step by Step", "Ciprian Adrian Rusen" });
        dt.Rows.Add(new object[] { 2, "Windows® Phone 7 Plain & Simple", "Michael Stroh" });

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

        object[] rowArray = new object[3];
        rowArray[0] = 10;
        rowArray[1] = "Troubleshooting Windows® 7 Inside Out";
        rowArray[2] = "Mike Halsey";
        DataRow tempRow = dt.NewRow();
        tempRow.ItemArray = rowArray;
        dt.Rows.Add(tempRow);

        Label1.Text = "After added a new DataRow to DataTable";

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DataRow ItemArray property in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to use DataRow ItemArray property in ado.net
        </h2>
        <hr width="500" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="Firebrick" Height="35" />
            <RowStyle BackColor="ForestGreen" />
            <AlternatingRowStyle BackColor="SeaGreen" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Medium"
             ForeColor="SeaGreen"
             >
        </asp:Label>
        <br /><br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            ShowHeaderWhenEmpty="true"
            >
            <HeaderStyle BackColor="Firebrick" Height="35" />
            <RowStyle BackColor="ForestGreen" />
            <AlternatingRowStyle BackColor="SeaGreen" />
        </asp:GridView>
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DarkBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to select rows from a DataTable

Select rows from 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 select rows from a DataTable instance. So we will get all the rows from a DataTable.

The DataTable class Select() method gets an array of DataRow objects. The DataTable Select() method returns an array of DataRow objects. The asp.net web developers don’t have to pass any parameter to this Select() method to get all the rows from a DataTable object.
UsingDataTableSelectMethod.aspx

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

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

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

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

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

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

        dt.Rows.Add(new object[] { 1, "NetBook", "500" });
        dt.Rows.Add(new object[] { 2, "Monitor", "100" });
        dt.Rows.Add(new object[] { 3, "Laptop", "700.25" });

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

        DataRow[] drows = dt.Select();
        for (int i = 0; i < drows.Length;i++ )
        {
            decimal productPrice = Convert.ToDecimal(dt.Rows[i]["Price"].ToString());
            dt.Rows[i]["Price"] = productPrice+(productPrice/100*10);
        }

        Label1.Text = "After updating rows (increasing price 10%)";

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

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

c# - Select rows that match filter criteria from a DataTable

Select rows that match filter criteria from 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 select data from a DataTable instance with the specified condition. So we will get the rows from the DataTable which match the filter criteria.

The DataTable class Select() method gets an array of DataRow objects. The Select(String) method overload gets an array of all DataRow objects that match the filter criteria.

The Select(string? filterExpression) method overload has a parameter named filterExpression. The filterExpression parameter is a String which is the criteria to use to filter the rows. This method returns an array of DataRow objects.

To create the filterExpression argument, the asp.net web developers have to use the same rules that apply to the DataColumn class's Expression property value for creating filters. If the column on the filter contains a null value then it will not be part of the result.

So finally, using the DataTable class Select(String) method overload’s the asp.net c# web developers can get data that match filter criteria from a DataTable instance.
DataRowArrayFromADataTableWithFilter.aspx

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

<!DOCTYPE html>
<script runat="server">
    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, "Oracle SQL Tuning Pocket Reference", "Mark Gurry" });
        dt.Rows.Add(new object[] { 2, "Java Programming with Oracle JDBC", "Donald Bales" });
        dt.Rows.Add(new object[] { 3, "Oracle DBA Checklists Pocket Reference", "Quest Software" });

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

        //this line return a DataRow array from DataTable
        DataRow[] drows = dt.Select("BookID < 3");
        for (int i = 0; i < drows.Length;i++ )
        {
            dt.Rows[i]["BookName"] = dt.Rows[i]["BookName"].ToString().ToLower();
        }

        Label1.Text = "After updating filtered rows (make BookName lower case , BookID < 3)";

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to get a DataRow objects array from DataTable that match the filter criteria in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to get a DataRow objects array from
            <br /> DataTable that match the filter criteria in ado.net
        </h2>
        <hr width="550" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="Purple" Height="35" />
            <RowStyle BackColor="Magenta" />
            <AlternatingRowStyle BackColor="MediumPurple" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="SkyBlue"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="Purple" Height="35" />
            <RowStyle BackColor="Magenta" />
            <AlternatingRowStyle BackColor="MediumPurple" />
        </asp:GridView>
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DarkBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to count rows in a DataTable

Count rows in 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 count rows in a DataTable. So we have to count the DataRow objects within a DataTable instance. Here we used the DataTable class Rows property to get its rows collection as a DataRowCollection object. Then we used DataRowCollection’s Count property to count the rows within the rows collections.

The DataTable class Rows property gets the collection of rows that belong to this table. The Rows property value is a DataRowCollection that contains DataRow objects. Each DataRow in the collection represents a row of data in the table.

The DataRowCollection class represents a collection of rows for a DataTable. The DataRowCollection Count property gets the total number of DataRow objects in this collection. The Count property returns an Int32, the total number of DataRow objects in this collection.

So finally, using the DataTable class Rows property the asp.net web developers can get the DataRowCollection object. And the DataRowCollection class Count property allows the web developers to count the rows within the specified DataTable.
CountDataRowObjectsFromDataTable.aspx

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

<!DOCTYPE html>
<script runat="server">
    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, "Oracle DBA Pocket Guide", "David C. Kreines" });
        dt.Rows.Add(new object[] { 2, "Oracle SQL*Plus: The Definitive Guide, Second Edition", "Jonathan Gennick" });
        dt.Rows.Add(new object[] { 3, "Oracle Utilities Pocket Reference", "Sanjay Mishra" });

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

        //this line count all DataRow from DataTable
        int totalRows = dt.Rows.Count;

        Label1.Text = "DataTable contains total DataRow objects: " + totalRows;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to count total DataRow objects from a DataTable in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to count total DataRow
            <br /> objects from a DataTable in ado.net
        </h2>
        <hr width="350" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="SaddleBrown" Height="35" />
            <RowStyle BackColor="Purple" />
            <AlternatingRowStyle BackColor="PaleVioletRed" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="X-Large"
             ForeColor="OrangeRed"
             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="DarkBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to delete a row from a DataTable

Delete a row from the 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 delete a row from a DataTable. So we will remove a DataRow object from a DataTable instance at the specified index position. In this example code, we will remove a row by using its index value from a DataTable object.

Here we used the DataTable class Rows property to get its rows collection as a DataRowCollection object. Then we used DataRowCollection’s RemoveAt() method to remove a DataRow object at the specified index position from the rows collections.

The DataTable class Rows property gets the collection of rows that belong to this table. The Rows property value is a DataRowCollection that contains DataRow objects. Each DataRow in the collection represents a row of data in the table. The DataRowCollection class represents a collection of rows for a DataTable.

The DataRowCollection RemoveAt(Int32) method removes the row at the specified index from the collection. The RemoveAt(int index) method has a parameter named index. The index parameter is an Int32 which is the index of the row to remove.

When a row is removed from a DataTable, all data in that row is lost. The asp.net web developers can also call the Delete() method of the DataRow class to just mark a row for removal. Calling the RemoveAt() method is the same as calling the Delete() method and then calling AcceptChanges. The asp.net web developers also can use the Clear() method to remove all members of the rows collection at one time.

So finally, using the DataTable class Rows property the asp.net web developers can get the DataRowCollection object. And the DataRowCollection class RemoveAt() method allows the asp.net web developers to remove a row from the row collection in a DataTable at the specified index position.
RemoveDataRowFromDataTable.aspx

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

<!DOCTYPE html>
<script runat="server">
    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, "Flash 8 Cookbook", "Joey Lott" });
        dt.Rows.Add(new object[] { 2, "Flash 8: The Missing Manual", "E. A. Vander Veer" });
        dt.Rows.Add(new object[] { 3, "Flash Out of the Box", "Robert Hoekman, Jr." });

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

        //this line remove the DataRow from DataTable which index is 2
        dt.Rows.RemoveAt(2);

        Label1.Text = "After delete the DataRow which index is 2";

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to remove (delete) a DataRow at the specified index from DataTable in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to remove (delete) a DataRow
            <br /> at the specified index from DataTable in ado.net
        </h2>
        <hr width="500" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="OliveDrab" Height="35" />
            <RowStyle BackColor="DarkOrchid" />
            <AlternatingRowStyle BackColor="MediumOrchid" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Medium"
             ForeColor="SeaGreen"
             >
        </asp:Label>
        <br /><br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="OliveDrab" Height="35" />
            <RowStyle BackColor="DarkOrchid" />
            <AlternatingRowStyle BackColor="MediumOrchid" />
        </asp:GridView>
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DarkBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to insert a new row into DataTable

Insert a new row into the 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 insert a new row into a DataTable. So we have to insert a new DataRow object into the DataTable’s specified index position.

Here we used the DataTable class Rows property to get its rows collection as a DataRowCollection object. Then we used DataRowCollection’s InsertAt() method to insert a new DataRow object at a specified index position of the rows collections.

The DataTable class Rows property gets the collection of rows that belong to this table. The Rows property value is a DataRowCollection that contains DataRow objects. Each DataRow in the collection represents a row of data in the table. The DataRowCollection class represents a collection of rows for a DataTable.

The DataRowCollection InsertAt(DataRow, Int32) method inserts a new row into the collection at the specified location. The InsertAt(System.Data.DataRow row, int pos) method has two parameters. The row parameter is a DataRow to add. And the pos parameter is an Int32 which is the zero-based location in the collection where the asp.net web developers want to add the DataRow.

The InsertAt(System.Data.DataRow row, int pos) method throws IndexOutOfRangeException if the pos is less than 0. The location/index specified by InsertAt() method is reflected by the order of rows in the DataRowCollection only. If the value specified for the pos parameter of the InsertAt() method is greater than the number of rows in the collection then the new row is added to the end.

So finally, using the DataTable class Rows property the asp.net web developers can get the DataRowCollection object. And the DataRowCollection class InsertAt() method allows the asp.net web developers to insert a new row at the specified location of the row collection in a DataTable.
InsertDataRowIntoDataTable.aspx

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

<!DOCTYPE html>
<script runat="server">
    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, "Learning Flash Media Server 3", "William Sanders" });
        dt.Rows.Add(new object[] { 2, "Essential ActionScript 3.0", "Colin Moock" });
        dt.Rows.Add(new object[] { 3, "Learning Flash Media Server 2", "William Sanders" });

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

        DataRow dr = dt.NewRow();
        dr["BookID"] = 4;
        dr["BookName"] = "Introduction to Flex 2";
        dr["Author"] = "Roger Braunstein";

        //this line add the new DataRow into DataTable at the specified location
        dt.Rows.InsertAt(dr,1);

        Label1.Text = "After inserting the new DataRow at location 1";

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to insert a new DataRow into DataTable at the specified location in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to insert a new DataRow into
            <br /> DataTable at the specified location in ado.net
        </h2>
        <hr width="500" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="MediumVioletRed" Height="35" />
            <RowStyle BackColor="Violet" />
            <AlternatingRowStyle BackColor="Thistle" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Medium"
             ForeColor="SeaGreen"
             >
        </asp:Label>
        <br /><br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="MediumVioletRed" Height="35" />
            <RowStyle BackColor="Violet" />
            <AlternatingRowStyle BackColor="Thistle" />
        </asp:GridView>
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DarkBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to change DataTable columns order

Change the order of the columns in 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 first use the NewRow() method to return a new DataRow object. 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 change the order of the columns within a DataTable. So we have to change a specified DataColumn object’s order/position in a DataTable instance.

Here we used the DataTable class Columns property to get its columns collection as a DataColumnCollection object. Then we used DataColumnCollection’s Item[Int32] property to get the specified DataColumn instance.

After getting the DataColumn by index we can change this column’s order within the DataTable instance. The DataColumn class SetOrdinal(Int32) method changes the ordinal or position of the DataColumn to the specified ordinal or position.

The DataColumn class SetOrdinal(int ordinal) has a parameter named ordinal. The ordinal parameter is an Int32 which specified the column’s ordinal.

The DataColumn class SetOrdinal() method throws ArgumentException when the asp.net developers set the ordinal to less than 0 or greater than the ordinal of the last column.

When the asp.net c# developers change a column's ordinal, the DataColumn is moved to the new position in the collection of columns. Any columns between the previous and new ordinal will be renumbered, to adjust for a column's new ordinal.
DataColumnSetOrdinal.aspx

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

<!DOCTYPE html>
<script runat="server">
    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;

        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, "Learning Flash CS4 Professional", "Rich Shupe" });
        dt.Rows.Add(new object[] { 2, "Search Engine Optimization for Flash", "Todd Perkins" });
        dt.Rows.Add(new object[] { 3, "Dreamweaver CS4: The Missing Manual", "David Sawyer McFarland" });

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

        Label1.Text = "<b><u>Columns with Ordinal....</u></b><br />";
        for (int i=0; i< dt.Columns.Count; i++)
        {
            Label1.Text += dt.Columns[i].ColumnName + " || ";
            Label1.Text += dt.Columns[i].Ordinal + "<br/ >";
        }

        dt.Columns[1].SetOrdinal(2);
        Label1.Text += "after Ordinal change......";
        GridView2.DataSource = dt;
        GridView2.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Using SetOrdinal() method - How to set change DataColumn Ordinal in DataTable in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            Using SetOrdinal() method - How to set
            <br /> change DataColumn Ordinal in DataTable in ado.net
        </h2>
        <hr width="525" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="DarkBlue" Height="35" />
            <RowStyle BackColor="DodgerBlue" />
            <AlternatingRowStyle BackColor="SkyBlue" />
        </asp:GridView>
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Medium"
             ForeColor="HotPink"
             >
        </asp:Label>
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="DarkBlue" Height="35" />
            <RowStyle BackColor="DodgerBlue" />
            <AlternatingRowStyle BackColor="SkyBlue" />
        </asp:GridView>
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DarkBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to add a new row into DataTable

Add a new row to the 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 add a new row into a DataTable. So we have to add a new DataRow object into the DataTable.

Here we used the DataTable class Rows property to get its rows collection as a DataRowCollection object. Then we used DataRowCollection’s Add() method to add a new DataRow object to the rows collections.

The DataTable class Rows property gets the collection of rows that belong to this table. The Rows property value is a DataRowCollection that contains DataRow objects. Each DataRow in the collection represents a row of data in the table. The DataRowCollection class represents a collection of rows for a DataTable.

The DataRowCollection Add() method adds a DataRow to the DataRowCollection. The Add(DataRow) method overload adds the specified DataRow to the DataRowCollection object. The Add(System.Data.DataRow row) method has a parameter named row. The row parameter is the DataRow to add.

The Add(System.Data.DataRow row) method throws ArgumentNullException if the row is null. The method throws ArgumentException if the row either belongs to another table or already belongs to this table. And it throws ConstraintException if the addition invalidates a constraint. It also throws NoNullAllowedException if the addition tries to put a null in a DataColumn where AllowDBNull is false.

To create a new DataRow, the asp.net web developers must use the NewRow() method of the DataTable class. When they use the NewRow method, a new DataRow object is returned using the schema of the parent DataTable. After developers create the DataRow object and set the values for each of its columns, then they have to use the Add() method to add the object to the collection.

So finally, using the DataTable class Rows property the asp.net web developers can get the DataRowCollection object. And the DataRowCollection class Add() method allows the asp.net web developers to add a new row to the row collection in a DataTable.
AddDataRowToDataTable.aspx

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

<!DOCTYPE html>
<script runat="server">
    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;

        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, "Learning ActionScript 3.0, Second Edition", "Rich Shupe" });
        dt.Rows.Add(new object[] { 2, "Flash CS5: The Missing Manual", "Chris Grover" });

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

        //add another one DataRow in DataTable
        DataRow dr = dt.NewRow();
        dr["BookID"] = 3;
        dr["BookName"] = "Google SketchUp: The Missing Manual";
        dr["Author"] = "Chris Grover";
        dt.Rows.Add(dr);

        Label1.Text = "add another one DataRow into DataTable";

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to add DataRow to DataTable in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to add DataRow to DataTable in ado.net
        </h2>
        <hr width="500" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="Crimson" Height="35" />
            <RowStyle BackColor="DodgerBlue" />
            <AlternatingRowStyle BackColor="SkyBlue" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Medium"
             ForeColor="HotPink"
             >
        </asp:Label>
        <br /><br />
        <asp:GridView 
            ID="GridView2"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="Crimson" Height="35" />
            <RowStyle BackColor="DodgerBlue" />
            <AlternatingRowStyle BackColor="SkyBlue" />
        </asp:GridView>
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DarkBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to get column maximum length in a DataTable

Get the maximum length of a column in 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 get the maximum size/length of columns from a DataTable. So we have to get the maximum length of each DataColumn object within a DataTable instance.

In this example, we used the DataTable class Columns property to get its columns collection as a DataColumnCollection object. Then we loop through the columns collection. In the looping time, we used DataColumnCollection’s Item[Int32] property to get the specified DataColumn instance.

After getting the DataColumn by index we can get its maximum size/length by using the DataColumn class MaxLength property. We also get the specified column’s name by using the DataColumn class ColumnName property.

The DataTable class Columns property gets the collection of columns that belong to this table. The Columns property value is a DataColumnCollection that contains the collection of DataColumn objects for the table. An empty collection is returned if no DataColumn objects exist.

The DataColumnCollection class represents a collection of DataColumn objects for a DataTable. The DataColumnCollection class Item[Int32] property gets the DataColumn from the collection at the specified index.

The DataColumn class MaxLength property gets or sets the maximum length of a text column. This property value is an Int32 which is the maximum length of the column in characters. If the column has no maximum length then the value is -1 and this is the default value.

The DataColumn class MaxLength property is ignored for non-text columns. An ArgumentException exception is raised if the asp.net web developers assign the MaxLength property to a non-string column.
DataColumnMaxLengthFromDataTable.aspx

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

<!DOCTYPE html>
<script runat="server">
    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;

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

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

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

        dt.Rows.Add(new object[] { "1", "Mining the Social Web", "Matthew Russell" });
        dt.Rows.Add(new object[] { "2", "Cassandra: The Definitive Guide", "Eben Hewitt" });
        dt.Rows.Add(new object[] { "3", "Data Analysis with Open Source Tools", "Philipp K. Janert" });

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

        Label1.Text = "<b><u>Columns with MaxLength in DataTable....</u></b><br />";
        for (int i=0; i< dt.Columns.Count; i++)
        {
            Label1.Text += dt.Columns[i].ColumnName + " || ";
            Label1.Text += dt.Columns[i].MaxLength + "<br/ >";
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to get DataColumn MaxLength (maximum length) from DataTable in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to get DataColumn MaxLength
            <br /> programmatically from DataTable in ado.net
        </h2>
        <hr width="450" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="SlateBlue"
            Width="525"
            >
            <HeaderStyle BackColor="DarkTurquoise" Height="35" />
            <RowStyle BackColor="PaleTurquoise" BorderStyle="Dotted" BorderWidth="2" />
            <AlternatingRowStyle BackColor="LightBlue" />
        </asp:GridView>
        <br />
        <asp:Label
             ID="Label1"
             runat="server"
             Font-Size="Large"
             ForeColor="Crimson"
             >
        </asp:Label>
        <br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate GridView"
            Height="45"
            Font-Bold="true"
            ForeColor="DarkBlue"
            />
    </div>
    </form>
</body>
</html>

c# - How to get a DataTable columns data type

Get DataColumn’s DataType from 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 first use the NewRow() method to return a new DataRow object. 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 get the data type of columns from a DataTable. So we have to get the data type of each DataColumn object within a DataTable instance.

Here we used the DataTable class Columns property to get its columns collection as a DataColumnCollection object. Then we loop through the columns collection. In the looping time, we used DataColumnCollection’s Item[Int32] property to get the specified DataColumn instance.

After getting the DataColumn by index we can get its data type by using the DataColumn class DataType property. We also get the specified column’s name by using the DataColumn class ColumnName property.

The DataTable class Columns property gets the collection of columns that belong to this table. The Columns property value is a DataColumnCollection that contains the collection of DataColumn objects for the table. An empty collection is returned if no DataColumn objects exist.

The DataColumnCollection class represents a collection of DataColumn objects for a DataTable. The DataColumnCollection class Item[Int32] property gets the DataColumn from the collection at the specified index.

The DataColumn class DataType property gets or sets the type of data stored in the column. This property value is a Type object that represents the column data type.
DataColumnDataTypeFromDataTable.aspx

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

<!DOCTYPE html>
<script runat="server">
    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;

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

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

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

        dt.Rows.Add(new object[] { "1", "Scaling CouchDB", "Bradley Holt" });
        dt.Rows.Add(new object[] { "2", "Writing and Querying MapReduce Views in CouchDB", "Bradley Holt" });
        dt.Rows.Add(new object[] { "3", "Data Source Handbook", "Pete Warden" });
        dt.Rows.Add(new object[] { "4", "Scaling MongoDB", "Kristina Chodorow" });

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

        Label1.Text = "<b><u>Columns with DataType in DataTable....</u></b><br />";
        for (int i=0; i< dt.Columns.Count; i++)
        {
            Label1.Text += dt.Columns[i].ColumnName + " || ";
            Label1.Text += dt.Columns[i].DataType + "<br/ >";
        }
    }
</script>

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

c# - How to get index of a column by name in a DataTable


Get column index by name from 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 first use the NewRow() method to return a new DataRow object. 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 get the index of a column by the column name from a DataTable. So we have to find the index of a specified DataColumn object by its name within a DataTable instance.




Here we used the DataTable class Columns property to get its columns collection as a DataColumnCollection object. Then we used DataColumnCollection’s IndexOf() method to get the specified column’s index using the column name within the columns collections.




The DataTable class Columns property gets the collection of columns that belong to this table. The Columns property value is a DataColumnCollection that contains the collection of DataColumn objects for the table. An empty collection is returned if no DataColumn objects exist.




The DataColumnCollection class represents a collection of DataColumn objects for a DataTable. The DataColumnCollection IndexOf() method searches for the specified DataColumn and returns the zero-based index of the first occurrence within the collection.




Here we used the IndexOf(String) method overload to get the specified column index by its name within a DataTable instance. The IndexOf(string? columnName) method overload has a parameter named columnName. This parameter is a String which is the name of the column to find.




The DataColumnCollection IndexOf(string? columnName) method returns an Int32 which is the zero-based index of the column with the specified name or -1 if the column does not exist in the collection.




So finally, using the DataTable Columns property the asp.net developers can get the DataColumnCollection object. And the DataColumnCollection class IndexOf() method allows the developers to get the index of a column’s object by its name within the specified DataTable.





IndexOfMethodDataTable.aspx



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

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

DataColumn dc = new DataColumn();
dc.ColumnName = "BookID";
dc.DataType = typeof(int);

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[] {dc,dc2,dc3});

dt.Rows.Add(new object[] { "1", "Native Video in HTML5", "David Griffiths" });
dt.Rows.Add(new object[] { "2", "Best iPhone Apps, Second Edition", "J.D. Biersdorfer" });
dt.Rows.Add(new object[] { "3", "Microsoft® Silverlight® 4 Step by Step", "Laurence Moroney" });
dt.Rows.Add(new object[] { "4", "Premiere Elements 8: The Missing Manual", "Chris Grover" });

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

//this line get the 'Author' DataColumn index in DataTable
int columnIndex = dt.Columns.IndexOf("Author");
Label1.Text = "'Author' DataColumn index in DataTable? = " + columnIndex;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to get the index of the DataColumn with the specific name from DataTable in ado.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">
Using IndexOf() method - How to get the index of the
<br /> DataColumn with the specific name from DataTable in ado.net
</h2>
<hr width="550" align="left" color="CornFlowerBlue" />
<asp:GridView
ID="GridView1"
runat="server"
BorderColor="Snow"
ForeColor="Snow"
Width="525"
HeaderStyle-BackColor="DarkOrchid"
RowStyle-BackColor="SlateBlue"
AlternatingRowStyle-BackColor="MediumSlateBlue"
>
</asp:GridView>
<br /><br />
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="IndianRed"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Populate GridView"
Height="45"
Font-Bold="true"
ForeColor="DarkBlue"
/>
</div>
</form>
</body>
</html>





c# - How to get column names from a DataTable


Get all DataColumns name from DataTable



.NET framework's DataTable represents one table of in-memory data. The DataTable class exists in the System.Data namespace. The DataTable Columns property allows us to get the collection of columns that belong to this table.




DataTable Columns property value type is System.Data.DataColumnCollection which represents a DataColumnCollection that contains the collection of DataColumn objects for the table. If DataTable contains no DataColumn objects, then this property returns an empty collection.




.NET framework's DataColumnCollection class represents a collection of DataColumn objects for a DataTable. DataColumnCollection determines the schema of a table by defining the data type of each column.




We can loop through a DataTable's DataColumnCollection to get all DataColumn's names from the DataTable. In the below example code, we applied a foreach loop through the DataColumnCollection to get all column names in a specified table.




The following ADO.NET C# example code demonstrates to us how can we get all DataColumn names from a DatTable programmatically at run time in an ASP.NET application.




DataColumnListFromDataTable.aspx



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

<!DOCTYPE html>
<script runat="server">
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;

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

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

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

dt.Rows.Add(new object[] { "1", "Droid 2: The Missing Manual", "Preston Gralla" });
dt.Rows.Add(new object[] { "2", "Building Android Apps with HTML, CSS, and JavaScript", "Jonathan Stark" });
dt.Rows.Add(new object[] { "3", "Learning the iOS 4 SDK for JavaScript Programmers", "Danny Goodman" });

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

Label1.Text = "<b>Columns in DataTable....</b><br />";
foreach (DataColumn dc in dt.Columns)
{
Label1.Text += dc.ColumnName + "<br />";
}
}
</script>

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




c# - How to count columns in a DataTable


Count columns in 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 first use the NewRow() method to return a new DataRow object. 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 count columns in a DataTable. So we have to count the DataColumns within a DataTable instance. Here we used the DataTable class Columns property to get its columns collection as a DataColumnCollection object. Then we used DataColumnCollection’s Count property to count the columns within the columns collections.




The DataTable class Columns property gets the collection of columns that belong to this table. The Columns property value is a DataColumnCollection that contains the collection of DataColumn objects for the table. An empty collection is returned if no DataColumn objects exist.




The DataColumnCollection class represents a collection of DataColumn objects for a DataTable. The DataColumnCollection Count property gets the total number of elements in a collection. The DataColumnCollection Count property is inherited from InternalDataCollectionBase. The Count property returns an Int32 which is the total number of elements in a collection.




So finally, using the DataTable Columns property the asp.net developers can get the DataColumnCollection object. And the DataColumnCollection class Count property allows the developers to count the columns within the specified DataTable.





CountDataColumnInDataTable.aspx



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

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

DataColumn dc = new DataColumn();
dc.ColumnName = "BookID";
dc.DataType = typeof(int);
dc.AllowDBNull = false;
dc.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[] {dc,dc2,dc3});

dt.Rows.Add(new object[] { "1", "Learning Flash CS4 Professional", "Rich Shupe" });
dt.Rows.Add(new object[] { "2", "3D Game-Based Filmmaking: The Art of Machinima", "Paul Marino" });
dt.Rows.Add(new object[] { "3", "Flash CS4: The Missing Manual", "Chris Grover" });

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

//this line count the total DataColumn in DataTable
int totalColumns = dt.Columns.Count;
Label1.Text = "Number of DataColumn exists in DataTable? = " + totalColumns;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to get the total number of DataColumn in DataTable in ado.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">
Using Count Property - How to get the total
<br /> number of DataColumn in DataTable in ado.net
</h2>
<hr width="500" align="left" color="CornFlowerBlue" />
<asp:GridView
ID="GridView1"
runat="server"
BorderColor="Snow"
ForeColor="Snow"
Width="525"
HeaderStyle-BackColor="SlateBlue"
RowStyle-BackColor="DarkGray"
AlternatingRowStyle-BackColor="DimGray"
>
</asp:GridView>
<br /><br />
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="IndianRed"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Populate GridView"
Height="45"
Font-Bold="true"
ForeColor="DarkBlue"
/>
</div>
</form>
</body>
</html>




c# - How to check if a column exists in a DataTable


Determine whether the DataTable contains a specified DataColumn





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 first use the NewRow() method to return a new DataRow object. 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 determine whether a DataTable contains a specific DataColumn. So we have to check whether a specified DataCoumn exists or not within a DataTable. Here we used the DataTable class Columns property to get its columns collection then we find the specified column within the DataTable’s columns collection.




The DataTable class Columns property gets the collection of columns that belong to this table. The Columns property value is a DataColumnCollection that contains the collection of DataColumn objects for the table. An empty collection is returned if no DataColumn objects exist.




The DataColumnCollection class represents a collection of DataColumn objects for a DataTable. The DataColumnCollection Contains(String) method checks whether the collection contains a column with the specified name.




The DataColumnCollection Contains(string name) method’s name parameter is a String which is the ColumnName of the column to look for. This method returns a Boolean value. It returns true if a column exists with this name otherwise the method returns false.




The Contains() method returns false when two or more columns have the same name but different namespaces. The method call does not succeed if there is any ambiguity when matching a column name to exactly one column.




So finally, using the DataTable Columns property the asp.net developers can get the DataColumnCollection object. And the DataColumnCollection class Contains(String) method allows the developers to determine whether a specific DataColumn exists in the specified DataTable or not.






ContainsMethodDataTable.aspx



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

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

DataColumn dc = new DataColumn();
dc.ColumnName = "BookID";
dc.DataType = typeof(int);

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[] {dc,dc2,dc3});

dt.Rows.Add(new object[] { "1", "Network Your Computers & Devices Step by Step", "Ciprian Adrian Rusen" });
dt.Rows.Add(new object[] { "2", "Microsoft® Expression® Web 4 Step by Step", "Chris Leeds" });
dt.Rows.Add(new object[] { "3", "My New iPad, Second Edition", "Wallace Wang" });

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

//this line check the 'BookName' DataColumn exists in DataTable or not
Boolean columnExists = dt.Columns.Contains("BookName");
Label1.Text = "'BookName' DataColumn exists in DataTable? = " + columnExists;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to check the DataTable contains a DataColumn with the specified name in ado.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">
Using Contains() method - How to check the DataTable
<br /> contains a DataColumn with the specified name in ado.net
</h2>
<hr width="550" align="left" color="CornFlowerBlue" />
<asp:GridView
ID="GridView1"
runat="server"
BorderColor="Snow"
ForeColor="Snow"
Width="525"
HeaderStyle-BackColor="Maroon"
RowStyle-BackColor="OrangeRed"
AlternatingRowStyle-BackColor="Orchid"
>
</asp:GridView>
<br /><br />
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="DarkSeaGreen"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Populate GridView"
Height="45"
Font-Bold="true"
ForeColor="DarkBlue"
/>
</div>
</form>
</body>
</html>





c# - How to set maximum size of a column in a DataTable

Set the maximum size of a DataColumn in 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 first use the NewRow() method to return a new DataRow object. 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 set the maximum size of a DataColumn in a DataTable instance. Here we used the DataColumn class MaxLength property to set the maximum size/length of a DataColumn in a DataTable object.

The DataColumn class MaxLength property gets or sets the maximum length of a text column. The MaxLength property value is an Int32 which is the maximum length of the column in characters. If the specified column has no maximum length, the property value is -1 and this is the default value.

But the DataColumn MaxLength property is ignored for non-text columns. The ArgumentException exception is raised if the asp.net developers assign MaxLength to a non-string column.
DataColumnMaxLengthProperty.aspx

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

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

        DataColumn dc = new DataColumn();
        dc.ColumnName = "BookID";
        dc.DataType = typeof(int);
        dt.Columns.Add(dc);

        DataColumn dc2 = new DataColumn();
        dc2.ColumnName = "BookName";
        dc2.DataType = typeof(string);
        //this line make DataColumn values maximum length 40 characters
        dc2.MaxLength = 40;
        dt.Columns.Add(dc2);

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "BookAuthor";
        dc3.DataType = typeof(string);
        dt.Columns.Add(dc3);

        dt.Rows.Add(new object[] { 1, "Programming Python, Fourth Edition", "Mark Lutz" });
        dt.Rows.Add(new object[] { 2, "Head First Python", "Paul Barry" });

        /*uncomment this line to get error message because 
        BookName column maximum length 40 characters*/
        //dt.Rows.Add(new object[] { 3, "Hadoop: The Definitive Guide, Second Edition", "Tom White" });

        dt.Rows.Add(new object[] { 4, "Real World Instrumentation with Python", "John M. Hughes" });

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use DataColumn MaxLength Property in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            How to use DataColumn MaxLength Property in ado.net
        </h2>
        <hr width="525" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="Crimson" ForeColor="Snow" Height="30" />
            <RowStyle BackColor="SaddleBrown" ForeColor="Snow" />
            <AlternatingRowStyle BackColor="Tan" ForeColor="Snow" />
        </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 DataColumn with default value

DataColumn DefaultValue Property
The .NET framework's DataColumn represents the schema of a column in a DataTable. DataColumn class exists in the System.Data namespace.

We can initialize a new DataColumn class by many constructors such as DataColumn(), DataColumn(String), DataColumn(String, Type), etc. DataColmun() constructor initializes a new DataColumn class instance as a type String.

The DataColumn DefaultValue property allows us to get or set the default value for the column when we are creating new rows. DefaultVlaue property value data type is a String which represents a value appropriate to the column's DataType.

DataColumn DefaultVlaue property throws an InvalidCastException exception when we are adding a row and the default value is not follow the column's data type.

When we create a new DataRow, a default value is automatically assigned to the column in which the DefaultVlaue property is set. If we set AutoIncrement value to true for a DataColumn, then we cannot set a default value for the column.

The following ADO.NET C# example code demonstrates to us how can we specify a default value for a DataColumn in an ASP.NET application.
DataColumnDefaultValue.aspx

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

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

        DataColumn dc = new DataColumn();
        dc.ColumnName = "BookID";
        dc.DataType = typeof(int);
        dt.Columns.Add(dc);

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

        DataColumn dc3 = new DataColumn();
        dc3.ColumnName = "BookAuthor";
        dc3.DataType = typeof(string);
        //this line make DataColumn default value 'author not found'
        dc3.DefaultValue = "author not found";
        dc3.AllowDBNull = false;
        dt.Columns.Add(dc3);

        dt.Rows.Add(new object[] { 1, "HTML5 Step by Step", "Faithe Wempen" });
        dt.Rows.Add(new object[] { 2, "asp.net example ebook", null });
        dt.Rows.Add(new object[] { 3, "Painting the Web", "Shelley Powers" });
        dt.Rows.Add(new object[] { 4, "coldfusion example ebook", null });

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>DataColumn DefaultValue - How to create data column with default value in ado.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkBlue; font-style:italic;">
            DataColumn DefaultValue - How to create
            <br /> data column with default value in ado.net
        </h2>
        <hr width="500" align="left" color="CornFlowerBlue" />
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BorderColor="Snow"
            ForeColor="Snow"
            Width="550"
            >
            <HeaderStyle BackColor="Magenta" ForeColor="Snow" Height="30" />
            <RowStyle BackColor="SandyBrown" ForeColor="Maroon" />
            <AlternatingRowStyle BackColor="Wheat" ForeColor="Maroon" />
        </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>