Friday 10 August 2012

save xml format in 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();                
                }
                   
           
                  
                }
       

No comments:

Post a Comment