Insert Selected records from Gridview to database

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

Scenario: - Records will be displayed in the gridview from an xml file. First we will select the checkbox of which record we want to insert. Then when we click insert button selected data present in the gridview will be inserted to the database.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="Red"
     HeaderStyle-ForeColor="White" BackColor="#FFCC66" >

     <Columns>

     <asp:TemplateField>

      <ItemTemplate>

      <asp:CheckBox ID="chb1" runat="server" />

      </ItemTemplate>

       </asp:TemplateField>

                <asp:BoundField DataField="sid" HeaderText="sid" />

                <asp:BoundField DataField="sname" HeaderText="sname" />

                <asp:BoundField DataField="smarks" HeaderText="smarks" />

                <asp:BoundField DataField="saddress" HeaderText="saddress" />
            </Columns>

        </asp:GridView>
    </div>
    <asp:Button ID="btn_show" runat="server" onclick="btn_show_Click" Text="Show" />
     <asp:Button ID="btn_insert" runat="server" onclick="btn_insert_Click"
        Text="Insert Selected Records" Font-Bold="True" />
    </form>
</body>
</html>


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_Selectedata_from_Gridview
{
    public partial class _Default : System.Web.UI.Page
    {
        string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlCommand com;
        int select;

        protected void btn_show_Click(object sender, EventArgs e)
        {
            DataSet reportData = new DataSet();
            reportData.ReadXml(Server.MapPath("student.xml"));
            GridView1.DataSource = reportData;
            GridView1.DataBind();
        }

        protected void btn_insert_Click(object sender, EventArgs e)
        {
           
            for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
            {
                GridViewRow row = GridView1.Rows[i];
                CheckBox Chbox = (CheckBox)row.FindControl("chb1");
                if (Chbox.Checked == true)
                {
                    select++;
                }
            }

            if (select == 0)
            {
                Page.RegisterStartupScript("Alert Message", "<script language='javascript'>alert('Please check one checkbox records');</script>");
                return;
            }

            for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
            {
                string sid = GridView1.Rows[i].Cells[1].Text;
                string sname = GridView1.Rows[i].Cells[2].Text;
                string smarks = GridView1.Rows[i].Cells[3].Text;
                string saddress = GridView1.Rows[i].Cells[4].Text;
                GridViewRow row = GridView1.Rows[i];
                CheckBox Chbox = (CheckBox)row.FindControl("chb1");
                if (Chbox.Checked == true)
                {
                    InsertData(sid, sname, smarks, saddress);
                }
            }
            Response.Write("Record inserted successfully");
            }

        void InsertData(String sid, String sname, String smarks,string saddress)
        {
            SqlConnection con = new SqlConnection(connStr);
            try
            {
                con.Open();
                com = new SqlCommand("insert into student values('" + sid + "','" + sname + "','" + smarks + "','" + saddress + "')", con);
                com.ExecuteNonQuery();
                con.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }  
    }
}
Ebook Download
View all
Learn
View all