Israel Rodriguez
Israel Rodriguez

Reputation: 209

Moving method to a separate class

I have a method in a Windows form called Beginning that reads names from xml and displays them in a listbox. I want to move that method to a separate class that just deals with reading xml names. Here is the function I want to move into a different class

public void readNames()
{
    string path = "runners.xml"; //path
    XDocument xDoc = XDocument.Load(path);
    foreach (XElement element in xDoc.Descendants("Name"))
    {
        myListBox.Items.Add(element.Value);
    }

}

Is there a way to do this? Also, how would I call it from my my Beginning form class?

Upvotes: 0

Views: 168

Answers (2)

codingbiz
codingbiz

Reputation: 26396

public class MyXMLNamesReader
{
    public static List<string> readNames(string path)
    {
        List<string> names = new List<string>();
        XDocument xDoc = XDocument.Load(path);
        foreach (XElement element in xDoc.Descendants("Name"))
        {
            names.Add(element.Value);

        }
        return names;
    }

}

Usage

List<string> names = MyXMLNamesReader.readNames("runners.xml");
foreach(string name in names)
{
   myListBox.Items.Add(name);
}

Upvotes: 1

Sani Huttunen
Sani Huttunen

Reputation: 24395

Something like this should work (untested):

public static class MyReaderClass
{
  public static List<string> ReadNames(string path)
  {
    var items = new List<string>();

    XDocument xDoc = XDocument.Load(path);
    foreach (XElement element in xDoc.Descendants("Name"))
    {
      items.Add(element.Value);
    }

    return items;
  }
}

Then you call it from your form:

myListBox.Items.AddRange(MyReaderClass.ReadNames("runner.xml"));

Upvotes: 1

Related Questions