Dynamic controls based on Xml Elements

| August 6, 2010 | 0 Comments

The whole topic revolves around the concept that you need to generate dynamic controls based on xml elements in your xml file. The elements can increase or decrease. And you need to handle events of dynamic controls created.

XmlReader snapshot

XmlReader – Read Xml file

XmlRetriever snapshot

Xml Retriever – Generate controls dynamically

Pre-Requisites

There is not so much high prerequisites. You should have:

  • Visual Studio 2005 or more
  • .NET Framework 2.0 installed on system
  • Little bit modifications according to your requirements

Concepts Covered

It would be worth to mention how type of topics covered here:

  1. Reading Xml file using System.Xml.XmlTextReader and saving result in RichTextBox
  2. Passing values from one Form to another Form in same Project.
  3. Reading Xml Document particular element or node by using classes of System.Xml.XmlPath
  4. As mentioned earlier creating dynamic controls on basis of number of elements in particular node.
  5. Handling events of dynamically created control.
  6. Browsing specific file from application by OpenFileDialog control.

Code Snippet

It is not possible to show each and every piece of code here. But I am showing both Main.cs (Main form) and Second.cs(Second form). Main form retrieves Xml file and read and display same in RichTextBox control. Then from Main form user is directed to Second form.
Second form read the Xml file contents and then extract values from specific node as mentioned by developer. Those values are stored in array and used for creating RadioButton controls. FlowLayoutPanel is used for automatic arrangement of controls.

Rest check out the code or you can download the same from the link at the last of article.

Xml File

<?xml version="1.0"?>
<Details>
<level>Required</level>
<list>
<listitem i='0'>adress1, street1, state, zip</listitem>
<listitem i='1'>adress1, street1, state1, zip1</listitem>
<listitem i='2'>adress2, street2, state2, zip2</listitem>
<listitem i='3'>adress3, street3, state3, zip3</listitem>
<listitem i='4'>adress4, street4, state4, zip4</listitem>
</list>
</Details>

Main.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace ee_XmlReadForm
{
    public partial class Main : Form
    {
        // Public static variable
        public static string strFilePath;

        public Main()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog1.FileName;
                XmlWriter(txtFilePath.Text);
            }
        }

        // WRITING XML FILE TO THE RICH TEXT BOX
        private void XmlWriter(string filePath)
        {
            rtbText.Clear();
            XmlTextReader reader = new XmlTextReader(filePath);
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element: // The node is an element.
                        rtbText.Text += "\n";
                        break;
                    case XmlNodeType.Text: //Display the text in each element.
                        rtbText.Text += reader.Value + "\n";
                        break;
                    case XmlNodeType.EndElement: //Display the end of the element.
                        rtbText.Text += "\n";
                        break;
                }
            }
        }

        private void btnTransfer_Click(object sender, EventArgs e)
        {
            if (txtFilePath.Text != String.Empty)
            {
                strFilePath = txtFilePath.Text;
                this.Hide();
                Second sec = new Second();
                sec.Show();
            }
            else
            {
                MessageBox.Show("You have not selected Xml file", "No File Found", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

Second.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;      //Namespace added
using System.Xml.XPath;

namespace ee_XmlReadForm
{
    public partial class Second : Form
    {
        ArrayList arrElements;
        public Second()
        {
            InitializeComponent();

            #region Setting FlowLayoutPanel flpRadioButton
            this.flpRadioButtons.AutoScroll = true;
            this.flpRadioButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.flpRadioButtons.FlowDirection = System.Windows.Forms.FlowDirection.TopDown;
            this.flpRadioButtons.WrapContents = false;
            #endregion
        }

        private void Second_Load(object sender, EventArgs e)
        {
            ReadXmlFile(Main.strFilePath);
        }

        private void ReadXmlFile(string filePath)
        {
            // Reading the file and saving it in reader
            // Benefit: Reduce Load on system
            XmlTextReader reader = new XmlTextReader(filePath);

            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            // Creating Navigator to navigate Xml
            XPathNavigator nav = doc.CreateNavigator();

            // Compile a XPath expression
            XPathExpression expr = nav.Compile("/Details/list/listitem");

            // Iterate on the specific node specified in expression
            XPathNodeIterator iterator = nav.Select(expr);

            // Clearing ArrayList
            arrElements = new ArrayList();
            arrElements.Clear();

            try
            {
                while (iterator.MoveNext())
                {
                    // Creating new XPathNavigator clone
                    XPathNavigator nav2 = iterator.Current.Clone();
                    arrElements.Add(nav2.Value);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // Directing to Function to create dynamic controls
            if (arrElements.Count &gt; 0)
                CreateRadioButtons(arrElements);
        }

        private void CreateRadioButtons(ArrayList elements)
        {
            for (int i = 0; i &lt; arrElements.Count; i++)
            {
                // Create Radio Button
                RadioButton rbutton = new RadioButton();
                rbutton.Size = new Size(250, 30);
                rbutton.Name = "radioButton" + i.ToString();
                rbutton.Text = arrElements[i].ToString();
                rbutton.CheckedChanged += new System.EventHandler(RadioButton_CheckedChanged);

                // Adding to container
                this.flpRadioButtons.Controls.Add(rbutton);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
            Main main = new Main();
            main.Activate();
            main.Show();
        }

        private void RadioButton_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton checkRadio = (RadioButton)sender; //get the radioButton that was checked

            String[] arrValues=new String[4];
            arrValues = checkRadio.Text.Split(',');

            if (arrValues.Length &gt; 0)

            {
                txtAddress.Text = arrValues[0].ToString();
                txtStreet.Text = arrValues[1].ToString();
                txtState.Text = arrValues[2].ToString();
                txtZip.Text = arrValues[3].ToString();
            }
        }
    }
}

Download Source Code

Tags:

Category: .NET

Leave a Reply

%d bloggers like this: