-2

I am currently working on a rather simple Windows Form that lets me type in information such as name and number into text fields and then add that to a list view. The information is entered in another Form and I had some issues figuring out how to access the listView in Form1 from Form2.

I found the following code to work just fine

Form1:

private void button1_Click(object sender, System.EventArgs e)
{
     Form2._Form1 = this;
     Form2 form2 = new Form2();
     form2.Show();
}

Form2:

    public static Form1 _Form1;

Now, I simply wonder 2 things. What does this actually do? and do I HAVE to use static? Sorry if this is a very vague question, just wanna know what I'm actually doing.

MacA
  • 15
  • 6
  • 1
    Please learn to read the C# language documentation. Your question is really overly broad, but fundamentally you seem to be asking what a `static` field is. See duplicate for an extensive overview of `static` members in general and fields in particular. The code you posted just sets a `static` field in the `Form2` to the current `Form1` instance. Presumably so that `Form2` can access members of the `Form1` instance. This is, frankly, a horrible practice...it's unlikely that `Form2` should have a direct reference to `Form1` at all, and if it does need it, it should be passed in a constructor. – Peter Duniho Aug 14 '20 at 15:30
  • See also https://stackoverflow.com/questions/1665533/communicate-between-two-windows-forms-in-c-sharp for better advice about how to deal with inter-object interactions, using Winforms `Form` objects as the main example (the advice applies generally, but that question is specifically about `Form` objects). – Peter Duniho Aug 14 '20 at 15:31

1 Answers1

0

What does this actually do?

It sets the static field (shared by all instances of Form2) to the form1 instance. Then creates a Form2 instance and shows it.

do I HAVE to use static?

No - you would only use static if all instances of Form2 should share the same reference back to the same Form1.

Since that's most likely not necessary, I think an instance field and a constructor parameter (to ensure that the field is set) is more appropriate:

private Form1 _Form1;
public Form2(Form1 form1)
{
   this._Form1 = form1;
}

Then in your click event handler:

private void button1_Click(object sender, System.EventArgs e)
{
     Form2 form2 = new Form2(this);
     form2.Show();
}

I would also encourage more descriptive form/field names as well :)

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Am I creating a class variable here? When I create an int or string I can easily tell what type of variable it is. But what type of variable is it when you put in the name of a class instead of int, string, bool etc? – MacA Aug 16 '20 at 19:52
  • It's a reference to an instance of that type (or null). The only difference between this and your code is your "variable" (a _field_ to be precise) is static - mine is not. – D Stanley Aug 17 '20 at 12:28