Share via


Access list in class from multiple forms

Question

Wednesday, February 19, 2014 8:30 AM

Hi all,

I am lost in accessing my list in a class from multiple forms.

I have 4 winforms and the class parameters are set from my main form,but i need to access my list in the class to assign list values to my other 3 winforms.I first had my values in strings but since i could not do multiple returns that did not work so i added the strings to a list and want to parse the list items to the different forms.

Here is a small part of my code :

public class DownloadClass
    {
        public static string Download(string search, PictureBox pic, PictureBox pic2, PictureBox pic3)
        {
            HtmlDocument doc = new HtmlWeb().Load("http://mywebsite.com/index.php?searchTerm=" + search);
            List<string> titlesList = new List<string>();
            List<string> movieList = new List<string>();
            List<string> pictureList = new List<string>();
            List<string> movieurlList = new List<string>();

            foreach (HtmlNode link in doc.DocumentNode.SelectNodes("/html/body/div/div[1]/div/div[1]/a[1]/h4"))
                titlesList.Add(link.InnerText);

            foreach (HtmlNode movie in doc.DocumentNode.SelectNodes("/html/body/div/div/div/a"))
                movieList.Add(movie.Attributes["href"].Value);

            foreach (HtmlNode picture in doc.DocumentNode.SelectNodes("/html[1]/body[1]/div[3]/div[1]/div/a[1]/img"))
                pictureList.Add(picture.Attributes[@"src"].Value);

I am currently learning so the code is pretty dirty and i have put most of my code in this class,so my question is there a way to access this class as it is from the rest of my forms?

What i need to do is,list item 1 to form1,list item 2 to form2 and list item 3 to form3.

It is the movieurlList i need to assign to the different forms

All replies (2)

Wednesday, February 19, 2014 8:57 AM âś…Answered

Hi,

Are you trying to access the movieurlList from other Forms/Class?

If so, You can define the list as public static in your first form, assume Form1.

    public partial class Form1 : Form
    {
        public static List<string> movieurlList;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }
    }

The initialize the list and add some items to it, probably in the Form load or in the constructor. (Form1)

movieurlList = new List<string>();

Add some items to the list where you need to:

movieurlList.Add("a");
movieurlList.Add("b");

Now when you navigate in the other forms, you can access the movieurList like this:

string item2 = Form1.movieurlList.ElementAt(1);

Hope it helps


Wednesday, February 19, 2014 10:57 AM

Thanks a lot!

I managed to do what i wanted to do with the examples you gave me.