Hi i have a C# windows form that has two list boxes on it.The left one contains a list of 16 student module codes that are available to enrol onto. The user selects a module from the left to transfer to the right box. I have it working up to this point, the module code transfers when the select button is clicked.

Once a module has been transferred i need to click on it and print out onto a label (placed to the right of it)the full module details that are held in an XML file.

I am able to read through the contents of the XML file and output that to the label (all contents) what i need it to do is just print out the "SELECTED module" details to the label. So i have to somehow read through the XML file and pick out the particular module/modules that the user selects? So if he/she selects 8 modules then i just want the details of all of those to display on the label?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ModuleSelector.Entities;
using System.Xml;
using System.IO;
using System.Xml.XPath;


namespace ModuleSelector
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        String mName, mCode, mDescription, mCapacity, mLectureSlot, mTutorialSlot;
        string workingDir = Directory.GetCurrentDirectory();

        private void FormMain_Load(object sender, EventArgs e)
        {
            int slot = (int)Timetable.timeSlots.Monday4_6;
            System.Console.WriteLine(slot);
        }


        private void listBoxModules_DragLeave(object sender, EventArgs e)
        {
            String module = (String)listBoxModules.SelectedItem;
        }


        private void listBoxModules_DrawItem(object sender, EventArgs e)
        {
            String module = (String)listBoxModules.SelectedItem;
        }

        private void buttonAddModule_Click(object sender, EventArgs e)
        {
            listBoxSelectedModules.Items.Add(listBoxModules.SelectedItem);

        }

        private void listBoxSelectedModules_DrawItem(object sender, DrawItemEventArgs e)
        {
            String module = (String)listBoxModules.SelectedItem;
        }


        private void listBoxModules_DrawItem(object sender, DrawItemEventArgs e)
        {
            String module = (String)listBoxModules.SelectedItem;
        }

        private void buttonRemoveModule_Click(object sender, EventArgs e)
        {
            listBoxSelectedModules.Items.Remove(listBoxModules.SelectedItem);
        }

        private void buttonSubmit_Click(object sender, EventArgs e)
        {

        }
    private void listBoxSelectedModules_SelectedIndexChanged(object sender, EventArgs e)
        {
         XmlTextReader textReader = new XmlTextReader(workingDir + @"\XMLModules.xml");
            while (textReader.Read())
            {
                textReader.MoveToElement();
                //gets module name from XML file
                if (textReader.Name == "moduleName")
                {
                    textReader.Read();
                    XmlNodeType nType = textReader.NodeType;

                    if (nType == XmlNodeType.Text)
                    {
                        mName += (" Module Name: " + textReader.Value.ToString());
                    }
                }
                //gets module code from XML file
                if (textReader.Name == "moduleCode")
                {
                    textReader.Read();
                    XmlNodeType nType = textReader.NodeType;

                    if (nType == XmlNodeType.Text)
                    {
                        mCode += (" Module Code: " + textReader.Value.ToString());
                    }
                }
                //gets module description from XML file
                if (textReader.Name == "moduleDescription")
                {
                    textReader.Read();
                    XmlNodeType nType = textReader.NodeType;
                    if (nType == XmlNodeType.Text)
                    {
                mDescription += (" Module Description: " +textReader.Value.ToString());
                    }
                }
                //Gets module capacity from XML file
                if (textReader.Name == "moduleCapacity")
                {
                    textReader.Read();
                    XmlNodeType nType = textReader.NodeType;
                    if (nType == XmlNodeType.Text)
                    {
                     mCapacity += (" Module Capacity: " + textReader.Value.ToString());
                    }

                }
                //Gets module Lecture slot from XML file
                if (textReader.Name == "lectureSlot")
                {
                    textReader.Read();
                    XmlNodeType nType = textReader.NodeType;
                    if (nType == XmlNodeType.Text)
                    {
                    mLectureSlot += (" Lecture Slot: " + textReader.Value.ToString());
                    }
                }

                //Gets tutorial slot from XML file
                if (textReader.Name == "tutorialSlot")
                {
                    textReader.Read();
                    XmlNodeType nType = textReader.NodeType;
                    if (nType == XmlNodeType.Text)
                    {
                    mTutorialSlot += (" Tutorial Slot: "+textReader.Value.ToString());
                    }
                }
                //Writes the data to the label
                this.formLabel.Text = mName +
                    "\n" + mCode +
                    "\n" + mDescription +
                    "\n" + mCapacity +
                    "\n" + mLectureSlot +
                    "\n" + mTutorialSlot;
            }
            textReader.Close();
          }       

        }
    }

/**
module><moduleCode>3SFE504</moduleCode>
<moduleName>Algorithms and Data Structures</moduleName>
<moduleCapacity>5</moduleCapacity>
<semester>1</semester>
<Prerequisite>none</Prerequisite>
<lectureSlot>0</lectureSlot>
<tutorialSlot>1</tutorialSlot>
<moduleDescription>Data structures, ADT's and implementations</moduleDescription>
**/

Recommended Answers

All 15 Replies

Use Linq to XML.

string file = @"c:\path\file1.xml";

            var result = from n in XDocument.Load(file).Descendants("module")
                         select new
                         {
                              ModuleCode=n.Element("moduleCode").Value,
                              ModuleName=n.Element("moduleName").Value
                         };

            foreach (var t in result)
            {
                Console.WriteLine(t.ModuleCode + " " + t.ModuleName);
            }

Hi, thankyou for this, i keep getting an Exception error:

"System.IO.FileNotFoundException" and that the path name is not correct, but i have checked in and it is correct.

How would i put a try/catch attached to this?

try/catch will help you not to stuck but will not tell you what to do with the error it will simply resume after finding the exception so try to look why you are facing this problem as well as use try/catch

I have no idea, thats why i am asking,i am new to C# and reading xml files...

Check the path of file once again.... write here your location string

Im using windows 7 and it places Visual studio files in my documents....so its long winded.


@"C:\Users\mandy\Documents\Visual Studio 2008\Projects\ModuleSelector_11.30pm_14.4.11\ModuleSelector\bin\Debug\XMLModules";

This is the part of the code that is outlined in the Exception error??

var result = from n in XDocument.Load(file).Descendants("module")
                     select new
                     {
                         ModuleCode = n.Element("moduleCode").Value,
                         ModuleName = n.Element("moduleName").Value
                     };

Try after changing location of the file

I can't change it as the xml file has to reside in the Debug/bin/ path.

thats where C# accesses it in that directory

Could someone help please??

Member Avatar for geekman92

you need to put .xml at the end of your file path.

if that doesn't work then try double clicking in the margin to the left of this line of code:

var result = from n in XDocument.Load(file).Descendants("module")

you should see a red dot appear and highlight that line in red. now run(and debug) the program. the program will stop when it gets to the red dot and you can then see in one of the windows at the bottom if the file location is correct.

Yes i corrected the file and checked the location which was correct...it compiles now and runs fine but the code doesn't actually do anything, i am still getting a print out of all modules and details of all files no matter if i just select one module from the list box...so i don't know...but thankyou for your help.

I see that you type Debug/bin/path....Shouldn't it be bin/Debug/path

How is your Xml structured? I tend to by habit use the same structure which looks like

<Favorites><Url Item="http://www.daniweb.com"/><Url Item="http://www.codeproject.com/>"/></Favorites>

In this manner it is easier for me to call as such

using System.Xml;
private List<String> Urls = new List<String>();
XmlDocument doc = new XmlDocument();
doc.Load("path to xml");
foreach(XmlNode node in doc.SelectNodes("/Favorites/Url"))
{
  Urls.Add(node.Attributes["Item"].InnerText);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.