Click here to Skip to main content
15,885,435 members
Articles / Programming Languages / C#
Tip/Trick

XML to DataSet or GridView and back

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
23 Jul 2012CPOL1 min read 53.1K   1.6K   13   1
How to populate a GridView/DataSet from XML and how to save GridView/DataSet values back to XML.

Introduction

This document covers how to populate a GridView from XML and how to save the GridView values back to XML.

Steps to configure

  1. Open Visual Studio and create a new Windows application.
  2. Image 1

  3. Add a DataGridView to the form.
  4. Image 2

  5. Create an XML file in your local drive (say C:\ drive) with the below code.
  6. XML
    <?xml version="1.0" encoding="utf-8" ?> 
    <Dataset>
    <Table1>
    <Server>Server1</Server>
    <Database>Database1</Database>
    </Table1>
    <Table1>
    <Server>Server2</Server>
    <Database>Database2</Database>
    </Table1>
    </Dataset>
  7. Add the following code in the form load event.
  8. C#
    private void Form1_Load(object sender, EventArgs e)
    {
       //the path in which XML file is saved
       string path = "C:\\XMLFile1.xml";
       DataSet ds=new DataSet();
                 //Reading XML file and copying to dataset
       ds.ReadXml(path);
       dataGridView1.DataSource = ds;
       dataGridView1.DataMember = "table1";
    }
  9. Add a button “Add” below the grid view as shown below.
  10. Image 3

  11. Add the following code in the button click event:
  12. C#
    private void button1_Click(object sender, EventArgs e)
    {
        //path of XML file
        string path = "C:\\XMLFile1.xml";
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        //Adding columns to datatable
        foreach (DataGridViewColumn col in dataGridView1.Columns)
        {
            dt.Columns.Add(col.DataPropertyName, col.ValueType);
        }
        //adding new rows
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            DataRow row1 = dt.NewRow();
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
                //if value exists add that value else add Null for that field
                row1[i] = (row.Cells[i].Value == null ? DBNull.Value : row.Cells[i].Value);
            dt.Rows.Add(row1);
        }
        //Copying from datatable to dataset
        ds.Tables.Add(dt);
        //writing new values to XML
        ds.WriteXml(path);
        MessageBox.Show("Successfully added ", "Success");
        this.Close();
    }
  13. Run the solution. The below form should be displayed.
  14. Image 4

  15. Now enter the new values in the DataGridView and click Add. Check the values are getting added.
  16. Image 5

    Image 6

  17. Now check the new value is getting added in the XML file.
  18. XML
    <?xml version="1.0" standalone="yes"?>
    <NewDataSet>
    <Table1>
        <Server>Server1</Server>
        <Database>Database1</Database>
    </Table1>
    <Table1>
        <Server>Server2</Server>
        <Database>Database2</Database>
        </Table1>
    <Table1>
        <Server>Server3</Server>
        <Database>Database3</Database>
    </Table1>
    </NewDataSet>

Using the above concept to create connection string from XML

This can be used to configure a connection string at run time from XML. So the user can add his server name and database at XML and create connections at run time.

Now add a dropdown and button above the DataGridView as shown below. Add the below code in the form load event to populate databases in the dropdown as below.

C#
//Populating databases value in dropdown
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.Load(path);
//Give Node name here 
XmlNodeList nodelist = XMLDoc.SelectNodes("NewDataSet/Table1");
foreach(XmlNode node in nodelist){
    comboBox1.Items.Add(node.SelectSingleNode("Database").InnerText);
}

Image 7

Image 8

Now add the below code to fetch the server name on the selected database in the dropdown and click on Connect.

C#
private void button2_Click(object sender, EventArgs e)
{
    string path = "C:\\XMLFile1.xml";
    string server="";
    XmlDocument XMLDoc = new XmlDocument();
    XMLDoc.Load(path);
    //Give Node name here 
    XmlNodeList nodelist = XMLDoc.SelectNodes("NewDataSet/Table1");
    foreach (XmlNode node in nodelist)
    {
        if ((node.SelectSingleNode("Database").InnerText) == comboBox1.SelectedItem.ToString())
        {
            server = node.SelectSingleNode("Server").InnerText;
        }
    }
}

Now using the database and server, create a new SqlConnection as usual.

Conclusion

By using the above code, the user can populate a GridView from XML and again save back the new values to the XML file. This will be very useful in creating a connection string also.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead EF (Education First)
India India
I graduated as Production Engineer and started my career as Software Developer then worked as tester for a while before moving into Windows application development using Microsoft Technologies. But for the last few years i am working on javascript, React, Node, AWS, Azure Chatbots

Comments and Discussions

 
Generalxml Pin
Member 1135881029-Jan-15 23:43
Member 1135881029-Jan-15 23:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.