Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

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#


To show XML data into DataGridView , First am designing one form with some fields , one Save button and one DataGridView Control.
The Designed form is :



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


How to insert data into xml file using Windows forms application in C# || Insert and Retrieve data from xml file to bind datagridview in Windows Forms C#


Insert data into XML file :

This article is shows about insert data into XML file instead of using SqlServer database.
For that first Design your form as per your requirements.
In this am adding daily expenses of a person for that am taking fields as Date,  Amount, Purpose, Source  Bank and one Save button like below:



For accessing XML file add the following namespace in top of your code:

                         using System.Xml;

Write the following code in your Save button Click:
private void btnsave_Click(object sender, EventArgs e)
        {

            string path = "Expences.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");
                doc.AppendChild(declaration);
                doc.AppendChild(comment);


            }
            else //If there is already a file
            {
                //    //Load the XML File
                doc.Load(path);
            }

            //Get the root element
            XmlElement root = doc.DocumentElement;

            XmlElement Subroot = doc.CreateElement("Expences");
            XmlElement Date = doc.CreateElement("Date");
            XmlElement Amount = doc.CreateElement("Amount");
            XmlElement Purpose = doc.CreateElement("purpose");
            XmlElement Source = doc.CreateElement("Source");
            XmlElement Bank = doc.CreateElement("Bank");

            //Add the values for each nodes
            Date.InnerText = Convert.ToDateTime(dateTimePicker1.Text).ToShortDateString();
            Amount.InnerText = txtAmount.Text;
            Purpose.InnerText = txtPurpose.Text;
            if (radioButton1.Checked)
            {
                Source.InnerText = "Cash";
                Bank.InnerText = " ";
            }
            else
            {
                Source.InnerText = "Bank";
                Bank.InnerText = comboBox1.SelectedItem.ToString();
            }


           
            Subroot.AppendChild(Date);
            Subroot.AppendChild(Amount);
            Subroot.AppendChild(Purpose);
            Subroot.AppendChild(Source);

            Subroot.AppendChild(Bank);
            root.AppendChild(Subroot);
            doc.AppendChild(root);

            //Save the document
            doc.Save(path);


            //Show confirmation message
            MessageBox.Show("Details  added Successfully");

            //Reset text fields for new input
            txtPurpose.Text = String.Empty;
            txtAmount.Text = String.Empty;
        }
       
      Then run your application and see output like below:

To see your saving data in XML file do the following steps:
Select your solution from Solution Explorer
Right click and Select Open Folder in Windows Explorer
Then your application folder will open in that double click on bin folder  then double click debug folder
Then you will see your Expenses XML document file à double click on it then you will see your Saving Data in your browser like below:

Retrieve data from XML file and show in DataGridview :
For showing these saving data into DataGridview, am taking one Show button and DataGridview Control in the form:
Write the following code in show button click:
     private void btnShow_Click(object sender, EventArgs e)
        {
                XmlReader xmlFile;
                xmlFile = XmlReader.Create("Expences.xml"new XmlReaderSettings());
                DataSet ds = new DataSet();
                ds.ReadXml(xmlFile);
                dataGridView1.DataSource = ds.Tables[0];
            }

Then you will see your data binding to DataGridview like below:



xml serialization in .net

XML Serialization

      Serialization is the process of taking the state of an object and persisting it in some fashion. The Microsoft .NET Framework includes powerful objects that can serialize any object to XML. The System.Xml.Serialization namespace provides this capability.

Follow these steps to create a console application that creates an object, and then serializes its state to XML:
  1. In Visual C#, create a new Console Application project.
  2. On the Project menu, click Add Class to add a new class to the project.
  3. In the Add New Item dialog box, change the name of the class to clsPerson.
  4. Click Add. A new class is created.

    Note In Visual Studio .NET , click Open.
  5. Add the following code after the Public Class clsPerson statement
               public   string FirstName;
                 public   string MiddleName;
                 public   string LastName;
 
  1. Switch to the code window for Program.cs in Visual Studio or for Class1.cs in Visual Studio .NET
  2. In the void Main method, declare and create an instance of the clsPerson class:
        clsPerson p = new clsPerson();

     Set the properties of the clsPerson object:
           p.FirstName = "Naresh";
           p.MiddleName = "Kumar";
           p.LastName = "Kamuni";
       
  1. The Xml.Serialization namespace contains an XmlSerializer class that serializes an object to XML. When you create an instance of XmlSerializer, you pass the type of the class that you want to serialize into its constructor:
System.Xml.Serialization.XmlSerializer x =
                new System.Xml.Serialization.XmlSerializer(typeof(clsPerson));

  1. The Serialize method is used to serialize an object to XML. Serialize is overloaded and can send output to a TextWriter, Stream, or XMLWriter object. In this example,
  2. you send the output to the console:
                      x.Serialize(Console.Out,p);
       Console.WriteLine();
                     Console.ReadLine();

To verify that your project works, press CTRL+F5 to run the project.
A clsPerson object is created and populated with the values that you entered.
This state is serialized to XML. The console window shows the following:

<?xml version="1.0" encoding="IBM437"?>
 <clsPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FirstName>Naresh</FirstName>
 <MiddleName>Kumar</MiddleName>
<LastName>Kamuni</LastName>
</clsPerson>
(OR) 

 you send the output to the Stream:
System.IO.FileStream stream =
                    new System.IO.FileStream("XMLFile1.xml", FileMode.Create);
 x.Serialize(stream, p);

then your XMLFile.xml file is created in your Debug folder

The following snopshot is shows code about send the output to Stream:


  1.