Will Anderson Will Anderson - 22 days ago 9
C# Question

How to modify objects created by a function in another function C#

I have been struggling with creating a list in run time, then modifying it later on. The program creates a ListView in the createlist() function and I am trying to modify it in a different function. Any help would be appreciated but I would prefer if someone could tell me how to avoid this problem in future :)
Code extracts:

public void createlist()
{

ListView MainList = new ListView();

DisplayPanel.Controls.Add(MainList);

MainList.View = View.Details;
MainList.GridLines = true;

MainList.Name = "MainList";
MainList.Size = DisplayPanel.Size;
int s1 = DisplayPanel.Size.Height;
int s2 = DisplayPanel.Size.Width;
MainList.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top);

MainList.Columns.Add("ProductName", 100);
MainList.Columns.Add("ProductName2", 100);
MainList.Columns.Add("ProductName3", 100);
MainList.Columns.Add("ProductName4", 100);

}

private void button1_Click(object sender, EventArgs e)
{

createlist(); //Calls function and creates the ListView

ListViewItem Source = new ListViewItem("Source", 0);
Source.Checked = true;
Source.SubItems.Add("7");
Source.SubItems.Add("8");
Source.SubItems.Add("9");

MainList.Items.AddRange(new ListViewItem[] {Source});

}


Error :
Error CS0103 The name 'MainList' does not exist in the current context

Thanks in advance :)

Answer

You will need to make this a member of the class in order to access it from a different function. See below:

class Foo{
    ListView MainList = new ListView();
    public void createlist()
        {

            MainList = new ListView();

            DisplayPanel.Controls.Add(MainList);

            MainList.View = View.Details;
            MainList.GridLines = true;

            MainList.Name = "MainList";
            MainList.Size = DisplayPanel.Size;
            int s1 = DisplayPanel.Size.Height;
            int s2 = DisplayPanel.Size.Width;
            MainList.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top);

            MainList.Columns.Add("ProductName", 100);
            MainList.Columns.Add("ProductName2", 100);
            MainList.Columns.Add("ProductName3", 100);
            MainList.Columns.Add("ProductName4", 100);

        }

private void button1_Click(object sender, EventArgs e)
        {

            createlist();   //Calls function and creates the ListView

            ListViewItem Source = new ListViewItem("Source", 0);
            Source.Checked = true;
            Source.SubItems.Add("7");
            Source.SubItems.Add("8");
            Source.SubItems.Add("9");

            MainList.Items.AddRange(new ListViewItem[] {Source});

        }
}