0

I create 2 forms and I want each of them be able to access to each other. This is my code currently:

public partial class Form1: Form
{
    public Form1()
    {
        InitializeComponent();
        form2 = new Form2(this);
    }
}

internal partial class Form2: Form
{
    Form1 form1;
    internal Form2(Form1 f1)
    {
        InitializeComponent();
        form1 = f1;
    }
}

(All controls, methods in form1 are public, in form2 are internal, if it helps)

The problem is I can access all controls in form1 from from2, but I can't do the same when form1 needs to access form2. In form1 I can access form2 with built-in methods such as .Show() .Focus() and .Hide(), but not elements like checkboxes and trackbars.

Did I do anything wrong when declaring forms, or this is a bug due to something else? If this is a bug can you suggest me some reasons why this bug exist; I;m confused 'cause I'm pretty sure things in InitializeComponent() were created quite correctly (in standard way, using VS designer).

Felix Fourcolor
  • 101
  • 1
  • 1
  • You should name your forms. – SLaks Jun 12 '17 at 16:23
  • The classes' names are Form1 and Form2. Form1 access to Form2 with variable form2, Form2 access to Form1 with variable form1 (lower case name of their classes' name). Is this what you're saying? – Felix Fourcolor Jun 12 '17 at 16:30
  • You should use names that describe what they actually do. – SLaks Jun 12 '17 at 16:40
  • When you typed in your question the SO search showed you [Passing data between two forms](https://stackoverflow.com/questions/5087934/). Don't ignore it. – Dour High Arch Jun 12 '17 at 16:49

1 Answers1

0

You shouldn't access internal implementation details (such as controls) directly from another class.

Instead, you should write public functions or properties that perform the tasks you need, and call them from the other form.
This will let you refactor one form without affecting the other one.

SLaks
  • 837,282
  • 173
  • 1,862
  • 1,933
  • You mean I should write function in program.cs? Can you explain more why I should do this instead? – Felix Fourcolor Jun 12 '17 at 16:31
  • No; you should make public functions in each class. Learn about encapsulation. – SLaks Jun 12 '17 at 16:39
  • Ok I misunderstood at the first time, but I still not understand your answer. You mean make form2's methods "public" will solve the problem? For what I've learned "internal" means can be accessed in the same project, so why it does not work for me? – Felix Fourcolor Jun 12 '17 at 17:01