In this article, we will learn how to loop through the rows of GridView using For Each loop while inserting new rows to DataTable using C#.

Insert Data from GridView to DataTable in C#

First, add a GridView and a button to your web page:

    <div>

        <asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField
                    DataField="CustomerId"
                    HeaderText="Customer Id"
                    ItemStyle-Width="30" />

                <asp:BoundField
                    DataField="CustomerName"
                    HeaderText="Customer Name"
                    ItemStyle-Width="150" />

                <asp:BoundField
                    DataField="CustomerEmail"
                    HeaderText="CustomerEmail"
                    ItemStyle-Width="150" />
            </Columns>
        </asp:GridView>

        <br />


        <asp:Button runat="server" ID="btnCopy" OnClick="CopyToDataTable" Text="Copy to Datatable" />

    </div>

Populate the GridView

The following C# code loads the data to GridView with the records from the Customers table.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            string conn_str = "Data Source=localhost;Initial Catalog=db;Integrated Security=True";

            using (SqlConnection con = new SqlConnection(conn_str))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT CustomerID, CustomerName, CustomerEmail FROM Customers"))
                {
                    cmd.Connection = con;
                    using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable();
                        sda.Fill(dt);
                        gv.DataSource = dt;
                        gv.DataBind();
                    }
                }
            }
        }

    }

Insert rows in DataTable using For Each loop

When the user clicks on the copy button, a new DataTable is created with the same columns as that of the GridView. For each loop is executed and copy each row from GridView to the DataTable.

    protected void CopyToDataTable(object sender, EventArgs e)
    {
        DataTable dtCustomers = new DataTable("Customers");

        foreach (TableCell tc in gv.HeaderRow.Cells)
        {
            dtCustomers.Columns.Add(tc.Text);
        }

        foreach (GridViewRow gvr in gv.Rows)
        {
            dtCustomers.Rows.Add();
            for (int i = 0; i < gvr.Cells.Count; i++)
            {
                dtCustomers.Rows[gvr.RowIndex][i] = gvr.Cells[i].Text;
            }
        }

    }

Related Articles

Last modified: November 23, 2019

Comments

Write a Reply or Comment

Your email address will not be published.