Link to home
Start Free TrialLog in
Avatar of trevor1940
trevor1940

asked on

C#: How to pass data between forms Part2 XML docs

Hi
Following on form here

On Form1 I'm loading an xml file and using it to do stuff

using System.Xml.Linq;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
       string RootDir =  "D:\Path\To\Root"; // or browse 
        public static XDocument xdoc = XDocument.Load(RootDir  + "\\My.xml");
        // Load the XML Document using Linq to XML
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            frm2.SetValues(textBox1.Text, XDocument xdoc); // not happy
            if (frm2.ShowDialog() == DialogResult.OK)
                textBox2.Text = frm2.GetText1Value();
            else
                textBox2.Text = "Canceled";
        }
    }
}

Open in new window




I need to use the XML xdoc on form2 clearly reading it from the file again is a bad idea having multiple copies is asking for trouble
So how do I pass it?

I read somewhere having gobble variables is not good practice so should you also send RootDir to form2?
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi trevor1940;
 
I believe your code should be more like the below sample, please see the comments.

Please note that I change the signature of the functionSet values because I am not sure why you are passing the textBox1.Text from Form1 to Form2.

Will Form2 be updating the XML In the xdoc to be sent back to Form1 for updating that XML document?
You have marked a line on Form! as "not happy", why is this what are you trying to achieve here?

using System.Xml.Linq;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        // This needs to be static as well because you made xdoc static and this is because
        // static objects can not access instance variables
        static string RootDir = @"C:\Working Directory"; 
        public static XDocument xdoc = XDocument.Load(RootDir + "\\MyXml.xml");

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            // I believe this is what you want here see frm2.SetValues code
            frm2.SetValues(xdoc); // not happy
            if (frm2.ShowDialog() == DialogResult.OK)
                textBox2.Text = frm2.GetText1Value();
            else
                textBox2.Text = "Canceled";
        }
    }
}


using System.Xml.Linq;

namespace WindowsFormsApp2
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        internal void SetValues(XDocument xdoc)
        {
            // Set textBox1 text value to the XML of xdoc
            textBox1.Text = xdoc.ToString();
        }

        internal string GetText1Value()
        {
            // Return the value of the XML xdoc as text 
            return textBox1.Text;
        }
    }
}

Open in new window

Avatar of trevor1940
trevor1940

ASKER

textBox1.Text from Form1 to Form2.

This was in the last question which showed me how to pass values  of textboxes between forms I was building on that



Will Form2 be updating the XML In the xdoc to be sent back to Form1 for updating that XML document?

Form2 will up date the XML both in memory and send a call to a save function so the disk version is up to date
So I need to send xdoc back to form 1 as xdoc then re read it on form1?
Is that correct?

You have marked a line on Form! as "not happy", why is this what are you trying to achieve here?

The program errored here

I was thinking can I not have all the functions relating to loading, reading and writing to the XDocument xdoc in a separate shared  class would that mean I only have 1 copy ?
Form2 will up date the XML both in memory and send a call to a save function so the disk version is up to date
So I need to send xdoc back to form 1 as xdoc then re read it on form1?
Is that correct?
Nope.

When you pass the document as shown by my example, then all three forms use the same document. Thus you can save it also in form 2 or 3.

I was thinking can I not have all the functions relating to loading, reading and writing to the XDocument xdoc in a separate shared  class would that mean I only have 1 copy ?
You can do that, but this can be right or wrong. This depends on the context and use-case. Maybe you should explain, what you store in your XML?
Hi trevor1940;

To your statement
Form2 will up date the XML both in memory and send a call to a save function so the disk version is up to date
So I need to send xdoc back to form 1 as xdoc then re read it on form1?
Is that correct?
Actually when you pass an XDocument object as you do on Form1 it is being passed by reference so you are not sending a copy but a reference to the actual object and therefore if you modify it in Form2 it is changes in memory and all variables that point to that object have the modifications.

You state on the line you commented with, "not happy", that "The program errored here", what was the error message/s?
Can you post the function, frm2.SetValues(textBox1.Text, XDocument xdoc);, from Form2 please?
@ste5an You declare  
private XDocument document;

Open in new window

in my novice brain this means  document is only accessible to form1

where as @Fernando Soto You declare  
public static XDocument xdoc = .......

Open in new window


This means 1 copy but accessible globally?

How would "RootDir" be accessible to form2?  

To answer your follow up questions
@Fernando Soto

Actually when you pass an XDocument object as you do on Form1 it is being passed by reference so you are not sending a copy but a reference to the actual object and therefore if you modify it in Form2 it is changes in memory and all variables that point to that object have the modifications.

OK so there is no need to send the xdoc object back to form1 when form2 is finished with it!

The error was because  I did this

frm2.SetValues(textBox1.Text, XDocument xdoc); // not happy

Open in new window


Should of done this

frm2.SetValues(textBox1.Text, XDocument xdoc); // not happy

Open in new window


@ste5an
FYI:  I'm doing this as a learning exercise so any best practice advise welcome      
The XML holds info about TV shows

Form1 scans hard drive adding folders to a listview also adding a TMDBid if it exist in the XML

if not form2 Will search for that TV show using the TMDB api by folder name (TextBox1 in the above test) or manual input if can't be located then update the XML passing basck the TMDBid to update the listview

Forms3 will do similar  but add Episode information and rename the file so it conforms to

Show.Name.SXXEXX.Title.ext

where X is a number

Open in new window



I may create individual XML files for each episode so it can be seen in by media player
Just test my sample. In C# mostly all variables are passed by reference. Thus you actual hand-over a pointer to the same memory location of your variable. Which means that you share that memory location, thus you share your variable. In the case of you XDocument instances, this means that both form use the same, single instance.

For your exercise:
Normally I (we) strive for clean code. This means in object oriented programming: SOLID. These principles of OOP are:

- Single Responsibility Principle (SRP)
- Open-Closed Principle (OCP)
- Lishkov Substition Principle (LSP)
- Interface Segregation Principle (ISP)
- Dependency Inversion Principle (ICP)

Read about these. But start with the first. It means that you should separate UI handling from logic. So the idea of a class holding that data is the correct approach. E.g. something like this (take a look at the Class Diagram file type):

User generated image
with

namespace WindowsFormsCS
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    public class ShowDatabase
    {
        public List<string> Directories { get; private set; } = new List<string>();
        public List<Show> Shows { get; private set; } = new List<Show>();

        public void AddDirectory(string directoryName)
        {
            if (Directory.Exists(directoryName))
            {
                this.Directories.Add(directoryName);
                this.ScanDirectories();
            }
        }

        private void ScanDirectories()
        {
            throw new NotImplementedException();
        }

        public void UpdateFiles()
        {
            throw new System.NotImplementedException();
        }

        public void UpdateTmdbData()
        {
            throw new System.NotImplementedException();
        }
    }
}

Open in new window

and

namespace WindowsFormsCS
{
    public class Show
    {
        public string ShowName { get; set; }
        public string TmdbIdent { get; set; }
    }
}

Open in new window


Then you just use an instance of ShowDatabase in all your forms.
I've created a class call XMLFuncs

Form1 calls LoadXml OK

but when Form2 calls ChecKShowName,  Xdoc is null

I assumed Xdoc  would remain in memory

Dose Form1 need to load the XML then pass it to form2 and XMLFuncs as a reference each time a query is run?

XMLFuncs
using System.IO;
using System.Xml.Linq;

namespace PassBetweenForms
{
    class XMLFuncs
    {
         public XDocument Xdoc;

        public void LoadXml(string XmlPath)
        {
            if (File.Exists(XmlPath)){
                Xdoc = XDocument.Load(XmlPath);
            }
        }

        public string ChecKShowName(string FolderName)
        {

            // // Checks for the existence of a Show and return it's TMDB ID
            var results = (from node in Xdoc.Descendants("Show")
                           where node.Element("FolderName").Value == FolderName
                           select node.Element("TMDBid").Value).FirstOrDefault();
            if (results != null)
            {
                return results;
            }
            else
            {
                return null;
            }
            
        }

    }
}

Open in new window


Form1
using System.Windows.Forms;
using System.Xml.Linq;


namespace PassBetweenForms
{
    public partial class Form1 : Form
    {
        static string RootDir = @"J:\Media\TV\";
        String PathToXML = RootDir + "TV.xml";
        private XMLFuncs xmlFuncs = new XMLFuncs();
        


        public Form1()
        {
            InitializeComponent();
            xmlFuncs.LoadXml(PathToXML);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Form2 frm2 = new Form2();
            frm2.SetValues(textBox1.Text);
            if (frm2.ShowDialog() == DialogResult.OK)
                textBox2.Text = frm2.GetText1Value();
            else
                textBox2.Text = "Canceled";
        }
    }
}

Open in new window


Form2
namespace PassBetweenForms
{
    public partial class Form2 : Form
    {
        //public static XDocument Xdoc;
        private XMLFuncs xmlFuncs = new XMLFuncs();
        public Form2()
        {
            InitializeComponent();
        }
        public void SetValues(string textBox1Text)
        {
          //  Xdoc = xdoc;
            textBox1.Text = textBox1Text;
            String TMDBid  = xmlFuncs.ChecKShowName(textBox1.Text);
            if (TMDBid != null)
            {
                textBox2.Text = TMDBid;
            }
            else
            {
                textBox2.Text = "Not Found";
            }
        }
        public string GetText1Value()
        {
            return textBox2.Text;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;

        }

    }
}

Open in new window

Hi trevor1940;

To your question, "Dose Form1 need to load the XML then pass it to form2 and XMLFuncs as a reference each time a query is run? ", you need to pass xmlFuncs to Form2 so that it knows how to access the XML document functions, so in answer to your question is yes. You can pass it in as a constructor parameter or create a method in Form2 which takes a XDocument parameter.
See my post above, how to pass instances.

Names should reflect what a method does or an class covers. "XMLFuncs" is would in indicate only functions over XML. Not an instance nor your shows.

btw, class names should reflect the entity they represent. Names should be camelCase and PascalCase. Abbreviations of three or more letters start with upper-case, the rest is lower-case.
Thank you both  for your time and help