List passed from MainClass to another class works only in constructor

  Uncategorised

I’m trying to access a list of objects (from the ChartControl.cs class) that is inside the MainForm.cs (the name of the list is: List<Book> Books), because I need some values from those Book objects in order to create a graph. However, when I try to access the information from the new list (such as the number of elements) from the ChartControl_Paint method, it displays 0 (Although the number of elements is displayed correctly in the constructor with parameters, as can be observed below).

If you need more code or any other information, don’t hesitate do tell me!
Thank you!

MainForm.cs

internal List<Book> Books { get; set; }

//.....some code.....

private void graphToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ChartGraphicsSampleForm cgsf = new ChartGraphicsSampleForm();
            ChartControl chartControl1 = new ChartControl(Books);
            cgsf.Show();
        }

ChartControl.cs:

List<Book> booksList = new List<Book>();

public ChartControl()
        {
            InitializeComponent();
            ResizeRedraw = true;
        }
public ChartControl(List<Book> list)
        {         
            booksList = list;
            int listCount = booksList.Count;
            MessageBox.Show("listCount: " + listCount); //the listCount shows the correct number of objects from the list
            InitializeComponent();
        }
private void ChartControl_Paint(object sender, PaintEventArgs e) {
            int listCount = booksList.Count;
            MessageBox.Show("listCount: " + listCount); //the listCount shows 0

            //.....some code.....

}

Source: Visual Studio Questions

LEAVE A COMMENT