C#: Unable to access Public method in a private method

88 views Asked by At

I'm new to C# and using Forms, so forgive me if I'm not understanding how this is supposed to work.

I'm trying to create a LayoutTablePanel in a Form to eventually display some data.

In Visual Studio, I know I can drag and drop a LayoutTablePanel into the Form Designer to visually see the table get added, but to make it easier to add/edit tables, I'd like to do it from with the public Form1() level like so:

public partial class Form1 : Form
{       
 public Form1()
 {
  InitializeComponent();
  TableLayoutPanel ClassCol = new TableLayoutPanel();
  ClassCol.Location = new System.Drawing.Point(0, 20);
  ClassCol.Name = "ClassCol";
  ClassCol.Size = new System.Drawing.Size(79, 400); //add a changing variable here later.
  ClassCol.TabIndex = 0;
  ClassCol.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
  Controls.Add(ClassCol);
 }

 private void toolStripLabel1_Click(object sender, EventArgs e)
 {

 }
}

Now, this initializes the TableLayoutPanel at runtime, which is what I want, but I'd like to modify (dynamically add rows) later on by clicking certain buttons. In this case, by clicking on toolStripLabel1_Click method; however, when typing in Class.Col within the private method there, it doesn't seem to have access to the iteration of the TableLayoutPanel instance I created. If someone could help me fix this, it'd be appreciated. Thanks.

Edit: If I adjust the code like so:

public partial class Form1 : Form
{     
  TableLayoutPanel ClassCol = new TableLayoutPanel();
  ClassCol.Location = new System.Drawing.Point(0, 20);
  ClassCol.Name = "ClassCol";
  ClassCol.Size = new System.Drawing.Size(79, 400); //add a changing variable here later.
  ClassCol.TabIndex = 0;
  ClassCol.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
  Controls.Add(ClassCol);

 public Form1()
 {
  InitializeComponent();
 }

 private void toolStripLabel1_Click(object sender, EventArgs e)
 {

 }
}

It says I'm using Form1.ClassCol as if it's a "type" when it's a "field".

1

There are 1 answers

9
Icemanind On BEST ANSWER

You need to move this line:

TableLayoutPanel ClassCol = new TableLayoutPanel();

Above this line:

public Form1()

You are declaring it locally inside your Form1() constructor, so no other method will be able to access it. You need to declare it at class level instead of method level.