Clark Kendall Fernandez Clark Kendall Fernandez - 3 months ago 8
C# Question

I've got 3 forms. Form2, forbutton2, and ProfileView

I showed forbutton2 on a panel inside the Form2, I wanted to put a button on my forbutton2 that will show the ProfileView on panel also inside a form 2.

private void button1_Click(object sender, EventArgs e)
{
ProfileView myForm = new ProfileView();
myForm.TopLevel = false;
myForm.AutoScroll = true;
Form2.panel4.Controls.Add(myForm);
myForm.Show();
}


this is the code on the button from forbutton2 form.

These were the errors prompted in the code I used:


Error 1: An object reference is required for the non-static field, method, or property '
Form2.panel4
'

Error 2: '
Form2.panel4
' is inaccessible due to its protection level

Answer
  1. Form2 is class name (probably declared as public partial Form2 : Form) and you are trying to access its field panel4.

  2. Second error says

    panel4 is inaccessible due to its protection level.

Which means Form2 has panel4 but it does not have public access modifier.

If button1_Click() method is inside Form2 (I believe it is) use this.panel4.Controls.Add(myForm);. This will eliminate both errors.

Otherwise you should get reference to Form1 which has panel4 inside (according to comments):

private void button1_Click(object sender, EventArgs e)
{
  ProfileView myForm = new ProfileView();
  myForm.TopLevel = false;
  myForm.AutoScroll = true;
  var form1 = Application.OpenForms.OfType<Form1>().Where(x => x.Name == "Name of Form1").FirstOrDefault();
  form1?.panel4.Controls.Add(myForm);
  myForm.Show();
}