Insert data from Gridview to database

By Satyapriya Nayak Mar 03, 2012
In this blog we will know how to insert data from Gridview to database.

In this blog we will know how to insert data from Gridview to database.


Scenario: - Records will be displayed in the gridview from an xml file. Then when we click insert button all data present in the gridview will be inserted to the database.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Insert_data_from_Gridview_database._Default" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">


<html xmlns="" >

<head runat="server">

    <title>Untitled Page</title>



    <form id="form1" runat="server">


    <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

    <asp:GridView ID="GridView1" runat="server">


    <asp:Button ID="btn_insert" runat="server" onclick="btn_insert_Click"

        Text="Insert Records" />

    <asp:Button ID="btn_show" runat="server" onclick="btn_show_Click"

        style="height: 26px" Text="Show Records" />








using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Data.SqlClient;

namespace Insert_data_from_Gridview_database


    public partial class _Default : System.Web.UI.Page


        string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        SqlCommand com;


        protected void btn_show_Click(object sender, EventArgs e)


            DataSet reportData = new DataSet();


            GridView1.DataSource = reportData;




        protected void btn_insert_Click(object sender, EventArgs e)


            foreach (GridViewRow g1 in GridView1.Rows)


                SqlConnection con = new SqlConnection(connStr);

                com = new SqlCommand("insert into student(sid,sname,smarks,saddress) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);






            Label1.Text = "Records inserted successfully";






Thanks for reading


Satyapriya Nayak
Satyapriya Nayak

Satyapriya Nayak is a software developer from Bhubaneswar, India. He holds a Bachelor's degree in Electronics and telecommunication and is an active member of C# Corner.