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.

Introduction

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".

CreateApplication

Step 2:

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

AddNewItem

Step 3:

Create a new XML file.as in the following figure.

CreateXMLFile

Step 4 :

Use the following code in the EmployeeDetails.xml file.

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

<EmployeeInformation>

  <Employee>

    <ID>101</ID>

    <UserName>Pankaj Lohani</UserName>

  </Employee>

  <Employee>

    <ID>102</ID>

    <UserName>Nimit Joshi</UserName>

  </Employee>

  <Employee>

    <ID>103</ID>

    <UserName>Pravesh Khanduri</UserName>

  </Employee>

  <Employee>

    <ID>104</ID>

    <UserName>Amit Senwal</UserName>

  </Employee>

  <Employee>

    <ID>105</ID>

    <UserName>Ravi Kumar</UserName>

  </Employee>

  <Employee>

    <ID>105</ID>

    <UserName>Ainul Hasan</UserName>

  </Employee>

  <Employee>

    <ID>106</ID>

    <UserName>Ashish Topwal</UserName>

  </Employee>

</EmployeeInformation>

Step 5 :

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

AddNewForm

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="http://www.w3.org/1999/xhtml" >

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

    <title>Untitled Page</title>

</head>

<body>

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

    <div>

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

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

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

<Columns>

<asp:TemplateField>

<ItemTemplate>

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

</ItemTemplate>

</asp:TemplateField>

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

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

</Columns>

<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:GridView>

    </div>

    <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>

    </form>

</body>

</html>

 

Add the ConnectionString in Web.config file suck like :

 

<connectionStrings>

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

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

</connectionStrings>

  

 

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();

            empinfo.ReadXml(Server.MapPath("EmployeeDetails.xml"));

            empdetails.DataSource = empinfo;

            empdetails.DataBind();

        }

 

        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)

                {

                    check++;

                }

 

            }

 

            if (check == 0)

            {

                Page.RegisterStartupScript("Alert Message",

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

                return;

            }

 

            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);

            try

            {

                    con.Open();

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

                    com.ExecuteNonQuery();

                    con.Close();

                

            }

            catch (Exception ex)

            {

                Response.Write(ex.ToString());

            }

        }   

    }

 

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:

AferDebug

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.

ValidateForm

Step 10 :

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

SaveDataInDatabase

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

 

Showtable

Step 11 :

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

CheckMultipleRecords

select * from EmpInfo

ShowRecordsInTable

Summary

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.