JEYAGANESH

JEYAGANESH
Software Developer

Tuesday, 6 November 2012

Enquiry / Contact Form with Javascript Validation Using Asp.net c#


Contact.aspx
-------------------

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>::Contact / Enquiry Page with JavaScript Form Validation:: Jeyaganesh asp.net Developer</title>
    <script language="javascript" type="text/javascript">
   function validate() {
       if (document.getElementById("<%=TextBox1.ClientID%>").value == "") {
           alert("Name Feild can not be blank");
           document.getElementById("<%=TextBox1.ClientID%>").focus();
           return false;
       }

       if (document.getElementById("<%=TextBox2.ClientID %>").value == "") {
           alert("Email id Feild can not be blank");
           document.getElementById("<%=TextBox2.ClientID %>").focus();
           return false;
       }

       if (document.getElementById("<%=TextBox3.ClientID %>").value == "") {
           alert("Mobile No Feild can not be blank");
           document.getElementById("<%=TextBox3.ClientID %>").focus();
           return false;
       }
       if (document.getElementById("<%=TextBox4.ClientID %>").value == "") {
           alert("Feedback Feild can not be blank");
           document.getElementById("<%=TextBox3.ClientID %>").focus();
           return false;
       }
       var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
       var emailid = document.getElementById("<%=TextBox2.ClientID %>").value;
       var matchArray = emailid.match(emailPat);
       if (matchArray == null) {
           alert("Your Email Address Seems Incorrect. Please try again.");
           document.getElementById("<%=TextBox2.ClientID %>").focus();
           return false;
       }


       return true;
   }
</script>
</head>
<body>
    <form id="form1" action="" runat="server">
<table width="500" border="0" style="text-align:left; font-size:16px; color:#C6913D; font-weight:bold;">
  <tr>
    <td align="left">Enquiry Form</td>
    <td></td>
  </tr>
  <tr>
    <td>Name</td>
    <td>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Email Id</td>
    <td><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Mobile No</td>
    <td><asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Comments</td>
    <td><asp:TextBox ID="TextBox4" runat="server" TextMode="MultiLine" Width="300px" Height="150px"></asp:TextBox></td>
  </tr>

  <tr>
    <td></td>
    <td><br/>
        <asp:Button ID="Button1" runat="server" Text="Submit" class="learn-more"
             OnClientClick="return validate()" onclick="Button1_Click"/>
    <%--<a title="Submit" class="learn-more" href="#">Submit</a>--%></td>
  </tr>
</table>
</form>
</body>
</html>

Contact.aspx.cs
------------------


using System;
using System.Collections;
using System.Configuration;
using System.Data;
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.Net.Mail;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;
using System.Data.SqlClient;


public partial class Contact : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {

            MailMessage mail1 = new MailMessage();
            mail1.To.Add("to mailid");
            mail1.From = new MailAddress("fromemailid@hotmail.com");
            mail1.Subject = "Feed Back On " + DateTime.Now.ToString();
            mail1.IsBodyHtml = true;
            string Body1;

            Body1 = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
            Body1 += "<title></title>"

        + "</head>"
        + "<body>"

        + "<table align=\"center\" style=\"width: 650px; height: 377px;\">"
        + "<tr>"
        + "<td>"
        + "Name"
        + "</td>"
        + "<td align=\"center\">:</td>"
        + "<td>"
        + TextBox1.Text
        + "</td>"
       + "</tr>"
        + "<tr>"
       + "<td>"
       + "</td>"
       + "<td align=\"center\"></td>"
       + "<td>"
       + "</td>"
       + "</tr>"

        + "<tr>"
       + "<td>"
       + "</td>"
       + "<td align=\"center\"></td>"
       + "<td>"
       + "</td>"
       + "</tr>"

       + "<tr>"
       + "<td>"
       + "Email Id</td>"
       + "<td align=\"center\">:</td>"
       + "<td>"
       + TextBox2.Text + "</td>"
       + "</tr>"

       + "<tr>"
       + "<td>"
       + "</td>"
       + "<td align=\"center\"></td>"
       + "<td>"
       + "</td>"
       + "</tr>"
        + "<tr>"
       + "<td>"
       + "</td>"
       + "<td align=\"center\"></td>"
       + "<td>"
       + "</td>"
       + "</tr>"

       + "<tr>"
       + "<td>"
       + "Mobile No</td>"
       + "<td align=\"center\">:</td>"
       + "<td>"
       + TextBox3.Text + "</td>"
       + "</tr>"

        + "<tr>"
       + "<td>"
       + "</td>"
       + "<td align=\"center\"></td>"
       + "<td>"
       + "</td>"
       + "</tr>"
        + "<tr>"
       + "<td>"
       + "</td>"
       + "<td align=\"center\"></td>"
       + "<td>"
       + "</td>"
       + "</tr>"

       + "<tr>"
       + "<td>"
       + "Feedback</td>"
       + "<td align=\"center\">:</td>"
       + "<td>"
       + TextBox4.Text + "</td>"
       + "</tr>"

       + "</table>"
       + "</body>"
       + "</html>";


            mail1.Body = Body1;
            // mail.Body += Body.ToString();      
            mail1.IsBodyHtml = true;

            mail1.Priority = MailPriority.Normal;
            SmtpClient smtp1 = new SmtpClient();
            smtp1.Port = 25;
            smtp1.Host = "smtp.live.com";
            smtp1.Credentials = new System.Net.NetworkCredential("fromemailid@hotmail.com", "password");
            smtp1.EnableSsl = true;
            smtp1.Send(mail1);

           ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script>alert('Your Information Sending Successfully');</script>");

        }
        catch (Exception ex)
        {
             ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script>alert('Email Not Sent');</script>");
        }
    }
}

You can set your own domain mailid and Password:

SET Port No:25

SET Smtp host: mail.yourdomain.com or webmail.yourdomain.com (EX:mail.ganesh.com)

SET EnableSsl=false




JAVASCRIPT FORM VALIDATION FOR ASP.NET WEB FORM


<!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>::JavaScript Form Validation:: Jeyaganesh asp.net Developer</title>
    <script language="javascript" type="text/javascript">
   function validate() {
       if (document.getElementById("<%=TextBox1.ClientID%>").value == "") {
           alert("Name Feild can not be blank");
           document.getElementById("<%=TextBox1.ClientID%>").focus();
           return false;
       }

       if (document.getElementById("<%=TextBox2.ClientID %>").value == "") {
           alert("Email id Feild can not be blank");
           document.getElementById("<%=TextBox2.ClientID %>").focus();
           return false;
       }

       if (document.getElementById("<%=TextBox3.ClientID %>").value == "") {
           alert("Mobile No Feild can not be blank");
           document.getElementById("<%=TextBox3.ClientID %>").focus();
           return false;
       }
       if (document.getElementById("<%=TextBox4.ClientID %>").value == "") {
           alert("Feedback Feild can not be blank");
           document.getElementById("<%=TextBox3.ClientID %>").focus();
           return false;
       }
       var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
       var emailid = document.getElementById("<%=TextBox2.ClientID %>").value;
       var matchArray = emailid.match(emailPat);
       if (matchArray == null) {
           alert("Your Email Address Seems Incorrect. Please try again.");
           document.getElementById("<%=TextBox2.ClientID %>").focus();
           return false;
       }


       return true;
   }
</script>
</head>
<body>
    <form id="form1" action="" runat="server">
<table width="500" border="0" style="text-align:left; font-size:16px; color:#C6913D; font-weight:bold;">
  <tr>
    <td align="left">Enquiry Form</td>
    <td></td>
  </tr>
  <tr>
    <td>Name</td>
    <td>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Email Id</td>
    <td><asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Mobile No</td>
    <td><asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>
  </tr>
  <tr>
    <td>Comments</td>
    <td><asp:TextBox ID="TextBox4" runat="server" TextMode="MultiLine" Width="300px" Height="150px"></asp:TextBox></td>
  </tr>

  <tr>
    <td></td>
    <td><br/>
        <asp:Button ID="Button1" runat="server" Text="Submit"
             OnClientClick="return validate()"/>
    </td>
  </tr>
</table>
</form>
</body>
</html>

Monday, 22 October 2012

Jquery validation end date should be greater than start date using datepicker

 To implement this one first open Visual Studio and create new website after that write following code in your aspx page



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery UI Datepicker - Select a Date Range</title>
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.19.custom.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.19.custom.min.js"></script>
<script type="text/javascript">
$(function() {
var dates = $("#txtFrom, #txtTo").datepicker({
minDate: '0',
maxDate: '+7D',
onSelect: function(selectedDate) {
var option = this.id == "txtFrom" ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings);
dates.not(this).datepicker("option", option, date);
}
});
});
</script>
<style type="text/css">
.ui-datepicker { font-size:8pt !important}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<label for="from">From</label>
<asp:TextBox ID="txtFrom" runat="server"/>
<label for="to">to</label>
<asp:TextBox ID="txtTo" runat="server"/>
</div>
</form>
</body>
</html>
If you observe above code in header section I added some of script files and css classes by using those files we will display calendar control with beautiful css style. You can get those files by downloading attached sample.
If you observe script in header section
$(function() {
var dates = $("#txtFrom, #txtTo").datepicker({
minDate: '0',
maxDate: '+7D',
minDate: I set it as 0 means it won’t allow us to select before today date
maxDate: Here I set as  '+7D' means it will allow us to select upto maximum 7 days.
If we want to set to 15 days or 1 Month range then we will use '+15D' or '+1M'
After completion of aspx page design and your code modifications just run your application and check your calendar control that would be like below demo
Demo


  jQuery  Countdown

The Final Countdown is plugin that let's you in control where and how you will display the countdown, this mean that the plugin doesn't make any assumption on how the html will be displayed and it's up to you to do it, with the help of our beloved jQuery selectors.

SHARE THIS LINK:

http://static.hilios.com.br/jquery-countdown/examples/basic.html 

DEMO:

  

Ajax AsyncFileUpload control example in asp.net to upload files to server

First create one new website after that right click on it add new folder and give name as ‘Files’ after that add AjaxControlToolkit reference to your application and add following line in your aspx page
<%@ Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" tagPrefix="ajax" %>
Once add above references design your aspx page will be likes this
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
// This function will execute after file uploaded successfully
function uploadComplete() {
document.getElementById('<%=lblMsg.ClientID %>').innerHTML = "File Uploaded Successfully";
}
// This function will execute if file upload fails
function uploadError() {
document.getElementById('<%=lblMsg.ClientID %>').innerHTML = "File upload Failed.";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="scriptManager1" runat="server"/>
<div>
<ajax:AsyncFileUpload ID="fileUpload1" OnClientUploadComplete="uploadComplete" OnClientUploadError="uploadError"
CompleteBackColor="White" Width="350px" runat="server" UploaderStyle="Modern" UploadingBackColor="#CCFFFF"
ThrobberID="imgLoad" OnUploadedComplete="fileUploadComplete" /><br />
<asp:Image ID="imgLoad" runat="server" ImageUrl="loading.gif" />
<br />
<asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
If you observe above code I define lot of properties to ajax:AsyncFileUpload now I will explain all the properties of Ajax fileupload control
OnClientUploadComplete – This property is used to execute the client side JavaScript function after file successfully uploaded.
OnClientUploadError – This property is used to execute the client side JavaScript function if file uploading failed.
OnClientUploadStarted – This property is used to execute the client side JavaScript function whenver file uploading start.
CompleteBackColor – This property is used to set fileupload control background after file upload complete its default value ‘Lime’.
ErrorBackColor – This property is used to set fileupload control background if file upload failed its default value ‘Red’.
UploadingBackColor – This property is the id of the control which is seen during upload file.
UploaderStyle – This property is used to set fileupload control appearance style either Modern or Traditional. By default its value "Traditional".
ThrobberIDID of control that is shown while the file is uploading.
Width – This property is used to set width of the control. By default its value ‘355px’
Now in code behind add following namespaces

C# Code
using System;
using System.Web.UI;
using AjaxControlToolkit;
After completion of adding namespaces write following code in code behind
protected void fileUploadComplete(object sender, AsyncFileUploadEventArgs e)
{
string filename = System.IO.Path.GetFileName(fileUpload1.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/") + filename);
}
VB Code
Imports System.Web.UI
Imports AjaxControlToolkit
Partial Class Default
Inherits System.Web.UI.Page
Protected Sub fileUploadComplete(ByVal sender As Object, ByVal e As AsyncFileUploadEventArgs)
Dim filename As String = System.IO.Path.GetFileName(fileUpload1.FileName)
fileUpload1.SaveAs(Server.MapPath("Files/") & filename)
End Sub
End Class
Demo
Download sample code attached

Tuesday, 19 June 2012

how to insert images into database and how to retrieve and bind images to gridview using asp.net (or) save and Retrieve images from database using asp.net

Introduction

Here I will explain how insert and retrieve images from database and how to bind images to gridview using asp.net
TableName : image_upload

Column Name
Data Type
Allow Nulls
Id
Int
Yes
imagesimageYes

After that Design your aspx page like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Image
        <asp:FileUpload ID="FileUpload1" runat="server" /><br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>


<div>
<asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
<Columns>
<asp:BoundField HeaderText = "id" DataField="id" />
<asp:TemplateField HeaderText="Image Id">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("id") %>' Height="150px" Width="150px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>

    </form>
</body>
</html>



web.config
------------


<connectionStrings>
        <add name="mmConnectionString" connectionString="server=SAMSUNG\SQLEXPRESS;Integrated Security=true;database=sample;" providerName="System.Data.SqlClient"/>
    </connectionStrings>



default.aspx.cs
---------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication4
{
   
    public partial class _Default : System.Web.UI.Page
    {
        string strcon = ConfigurationManager.ConnectionStrings["mmConnectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
           

if (!IsPostBack)
{
BindGridData();
}
        }
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT images,ID from [Image]", connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
gvImages.Attributes.Add("bordercolor", "black");
}

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                int image_length = FileUpload1.PostedFile.ContentLength;
                byte[] imgtype=new byte[image_length];
                HttpPostedFile img = FileUpload1.PostedFile;
                img.InputStream.Read(imgtype, 0, image_length);
                SqlConnection con = new SqlConnection(strcon);
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = "insert into image_upload values(1,'"+imgtype+"')";
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                int count = cmd.ExecuteNonQuery();
                con.Close();
                if (count == 1)
                {

                     BindGridData();
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "alert('image inserted successfully')", true);
                }
            }
        }
    }
}





handler.ashx.cs
---------------


string strcon = ConfigurationManager.AppSettings["mmConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Images from image_upload where ID=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}

Bind XML saving data to DataGridView with Delete and Edit Options in Windows forms applicatons using C# || Insert,Edit,Delete data into XML with DataGridView in Windows forms using C#




n this article am showing following steps:
  1. Save data into XML file .
  2. Retrieve data from XML file and bind that data to DataGridview.
  3. Add two EDIT and DELETE columns to DataGridView.
  4. Write edit,delete coding in dataGridView1_CellContentDoubleClick.
Save data into XML file:
For using XML add the following namespace:
                  using System.Xml;
Write the following code in Save button Click:
private void btnSave_Click(object sender, EventArgs e)
        {
       
                  string path = "AccountDetails.xml";
                XmlDocument doc = new XmlDocument();
                ////If there is no current file, then create a new one
                if (!System.IO.File.Exists(path))
                {
                    //Create neccessary nodes
                    XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
                    XmlComment comment = doc.CreateComment("This is an XML Generated File");
}
                else //If there is already a file
                {
                    //    //Load the XML File
                    doc.Load(path);
}
                    //Get the root element
                    XmlElement root = doc.CreateElement("BankAccount_Details");
                    XmlElement Subroot = doc.CreateElement("BankAccount");
                    XmlElement BankName = doc.CreateElement("BankName");
                    XmlElement AccountNumber = doc.CreateElement("AccountNumber");
                    XmlElement BankType = doc.CreateElement("BankType");
                    XmlElement Balance = doc.CreateElement("Balance");
                    //Add the values for each nodes
                    BankName.InnerText = comboBox1.SelectedItem.ToString();
                    AccountNumber.InnerText = txtAccNumber.Text;
                    if (rbtnCurrent.Checked)
                        BankType.InnerText = rbtnCurrent.Text;
                    else if (rbtnSaving.Checked)
                        BankType.InnerText = rbtnSaving.Text;
                    else
                        BankType.InnerText = rbtnOther.Text;
                    Balance.InnerText = txtBalance.Text;
                    //Construct the document
                    doc.AppendChild(declaration);
                    doc.AppendChild(comment);
                    doc.AppendChild(root);
                    root.AppendChild(Subroot);
                    Subroot.AppendChild(BankName);
                    Subroot.AppendChild(AccountNumber);
                    Subroot.AppendChild(BankType);
                    Subroot.AppendChild(Balance);
                    doc.Save(path);
                //Show  message
                MessageBox.Show("Records added Successfully");
                //Reset text fields for new input
                txtBalance.Text = String.Empty;
                txtAccNumber.Text = String.Empty;
                comboBox1.SelectedIndex = 0;
                                //To show added record in Gridview call LoadGrid() method which I show below
LoadGrid();
}
 

Retrieve data from XML file and bind  to DataGridview:
For  retrieve XML data  and bind to Gridview call the following method:
protected void LoadGrid()
        {
            DataSet xmlds = new DataSet();
            string path = "AccountDetails.xml";
            if (System.IO.File.Exists(path))
            {
                xmlds.ReadXml(path);
                if (xmlds.Tables.Count > 0)
                {
                    dataGridView1.DataSource = xmlds.Tables[0].DefaultView;
                   
                }
            }
       
        }
Call the above method in form page load also
private void Account_Details_Load(object sender, EventArgs e)
        {
            LoadGrid();
        }
       
Add  EDIT and DELETE columns to DataGridView:
For Editing and Deleting add two columns to DataGridView with Suitable Images. I am adding Delete Image in 1st  column and Edit in 2nd column.
For deleting and editing am taking account number as a parameter.
write the following code in dataGridView1_CellContentDoubleClick event:
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
              
//For Deleting following code
                if (e.ColumnIndex == 0)
                {
                    DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                    string acnum = row.Cells[3].Value.ToString();
                    string path = "AccountDetails.xml";
                    XmlDocument doc = new XmlDocument();
                    doc.Load(path);
                    XmlNode node = doc.SelectSingleNode("/BankAccount_Details/BankAccount[AccountNumber='" + acnum + "']");
                    node.ParentNode.RemoveChild(node);
                    doc.Save(path);
                    MessageBox.Show("Selected Record Deleted Successfully");
                }  
                  
          
          //For Editing following code
                if (e.ColumnIndex == 1)
                {
                    DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
                    int acnum = Convert.ToInt32(row.Cells[3].Value);
                    string path = "AccountDetails.xml";
                    XmlDocument doc = new XmlDocument();
                    doc.Load(path);
                    XmlNode node = doc.SelectSingleNode("/BankAccount_Details/BankAccount[AccountNumber='" + acnum + "']");
                    node.ParentNode.RemoveChild(node);
                    doc.Save(path);
                  
                    
                    ////If there is no current file, then create a new one
                    if (!System.IO.File.Exists(path))
                    {
                        //Create neccessary nodes
                         XmlDeclaration declaration  = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
                     XmlComment comment = doc.CreateComment("This is an XML Generated File");
                       
                        doc.AppendChild(declaration);
                        doc.AppendChild(comment);
                    }
    //If there is already a file
                         else 
                        {
                        //    //Load the XML File
                        doc.Load(path);
                        }
                        XmlElement root = doc.CreateElement("BankAccount_Details");
                        XmlElement Subroot = doc.CreateElement("BankAccount");
                        XmlElement BankName = doc.CreateElement("BankName");
                        XmlElement AccountNumber = doc.CreateElement("AccountNumber");
                        XmlElement BankType = doc.CreateElement("BankType");
                        XmlElement Balance = doc.CreateElement("Balance");
                        //Add the values for each nodes
                        BankName.InnerText = row.Cells[2].ToString();
                        AccountNumber.InnerText = row.Cells[3].ToString();
                        BankType.InnerText = row.Cells[4].ToString();
                        Balance.InnerText = row.Cells[5].ToString();
                        //Construct the document
                        doc.AppendChild(root);
                        root.AppendChild(Subroot);
                        Subroot.AppendChild(BankName);
                        Subroot.AppendChild(AccountNumber);
                        Subroot.AppendChild(BankType);
                        Subroot.AppendChild(Balance);
                        doc.Save(path);
                        MessageBox.Show("Selected Record Edited Successfully");
                    }
                                        
                                         LoadGrid();                
                }
                   
           
                  
                }
       
Then run your application and see output :