Insert XML Document in SQL Server in ASP.Net


This article shows how to read a XML file (EmployeeDetaisl.xml) residing in the application and the XML data will be displayed in a GridView control then selected rows will be inserted in a SQL Server database.

The ReadXml method reads an XML file and loads it into a DataSet. "MapPath" is a method of the "System.Web.HttpServerUtility" class, you need an instance of this class to call the method. In ASP pages an instance is available in the server member of the page that uses the "Server" variable for the current HttpContext.

Now  I will show you how to bind  the  records on a GridView control from the XML file after binding the records in a GridView control then selected records from the GridView will be inserted into the SQL Server database. Use the following procedure to do that.

Create DataBase and Table in SQL Server

Create Database Employee

Use Employee

create table EmpInfo


UserId int,

UserName nvarchar(max)


Step 1:

Open Visual Studio then select "Create New Website" --> "ASP.NET Web Site".


Step 2:

Now go to Solution Explorer to the right side of the application and do as shown in the following figure.


Step 3:

Create a new XML in the following figure.


Step 4 :

Use the following code in the EmployeeDetails.xml file.

<?xml version="1.0" encoding="utf-8" ?>




    <UserName>Pankaj Lohani</UserName>




    <UserName>Nimit Joshi</UserName>




    <UserName>Pravesh Khanduri</UserName>




    <UserName>Amit Senwal</UserName>




    <UserName>Ravi Kumar</UserName>




    <UserName>Ainul Hasan</UserName>




    <UserName>Ashish Topwal</UserName>



Step 5 :

Add a new Web form in the empty web application as in the following figure.


Step 6 :

Write the following code in the Default.aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 

Inherits="_Default" %>


<!DOCTYPE html>


<html xmlns="" >

<head id="Head1" runat="server">

    <title>Untitled Page</title>



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


    <asp:GridView ID="empdetails" runat="server" AutoGenerateColumns="False" 

     HeaderStyle-ForeColor="White" CellPadding="4" ForeColor="#333333" GridLines="None" >

<AlternatingRowStyle BackColor="White" ForeColor="#284775" />




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



<asp:BoundField DataField="Id" HeaderText="EmployeeId" />

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


<EditRowStyle BackColor="#999999" />

<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

<HeaderStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True"></HeaderStyle>

        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />

        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />

        <SortedAscendingCellStyle BackColor="#E9E7E2" />

        <SortedAscendingHeaderStyle BackColor="#506C8C" />

        <SortedDescendingCellStyle BackColor="#FFFDF8" />

        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />



    <asp:Button ID="EmpDetailsbtn" runat="server" onclick="EmpDetails" 

Text="Show Employee Details" />

     <asp:Button ID="Savebtn" runat="server" onclick="SaveRecord" 

        Text="Insert Selected Records" Font-Bold="True" />

        <asp:Label ID="lblmsg" runat="server"></asp:Label>





Add the ConnectionString in Web.config file suck like :



 <add name="dbconnection" connectionString="Data Source=; Initial Catalog=Employee; 

User=abc; Password=****" providerName="SqlClient"/>




Step 7 :

Now use the following code in Default.aspx.cs:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Xml;

using System.Web.UI.WebControls;


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


    protected void Page_Load(object sender, EventArgs e)


        lblmsg.Visible = false;


    string conString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;

        SqlCommand com;

        int check;


        protected void EmpDetails(object sender, EventArgs e)


            DataSet empinfo = new DataSet();


            empdetails.DataSource = empinfo;




        protected void SaveRecord(object sender, EventArgs e)



            for (int i = 0; i <= empdetails.Rows.Count - 1; i++)


                GridViewRow row = empdetails.Rows[i];

                CheckBox Chbox = (CheckBox)row.FindControl("Chkbox");

                if (Chbox.Checked == true)







            if (check == 0)


                Page.RegisterStartupScript("Alert Message",

         "<script language='javascript'>alert('Please Check atleast one record');</script>");




            for (int i = 0; i <= empdetails.Rows.Count - 1; i++)


                string eid = empdetails.Rows[i].Cells[1].Text;

                string uname = empdetails.Rows[i].Cells[2].Text;

                GridViewRow gvrow = empdetails.Rows[i];

                CheckBox Chbox = (CheckBox)gvrow.FindControl("Chkbox");

                if (Chbox.Checked == true)


                    SaveData(eid, uname);


                lblmsg.Text = "Data Inserted Successfully..";

                lblmsg.Visible = true;




        void SaveData(String eid, String uname)


            SqlConnection con = new SqlConnection(conString);




                    com = new SqlCommand("insert into EmpInfo values('" + eid + "','" + uname + "')", con);





            catch (Exception ex)







The GridView "Rows" property provides access to the data rows in the GridView. The Rows property returns a collection of GridView instances that make up the Gridview's datarows. The row's CheckBox is programmitically accessed using gridrows.FindControl("Chkbox"). Checkboxes allow the user to select one or more rows  from the gridvew control and you can access the CheckBoxes in code to determine whether a given checkbox is checked or to change the checked state.


Step 8 :

Debug the application by pressing F5 to execute the Web form. After debugging the application the output will be as in the following figure:


Step 9 :

If you will click the "Insert button" without checking any record then a form will generate a validation as in the following figure.


Step 10 :

Check the records that you want to insert into the database as in the following figure.


Now if you want to show the table in a database just write the query and press Enter as in the following figure:

select * from EmpInfo



Step 11 :

Check the Multiple Records to insert in database as in the following figure.


select * from EmpInfo



This article has shown how to read the XML file and bind XML data in a GridView control. After binding, only selected GridView rows will be inserted into a SQL Server database.