-1

I created a new Windows Form Project in Visual Studio. In this project, I create a new Class to put all my code in it.

In my Form1.cs, I call my Class like this:

 MyNewClass mnc = new MyNewClass();

In my button code, I put something like this:

 mnc.MyMethods();

In my class, I call my form like this:

 Form1 form1 = new Form1();

In my methods, I made this code:

 form1.MyTextBox.Text = "Salut toi";
 form1.Refresh();

But nothing appears in my form.

3
  • You already declared From? Commented May 8, 2020 at 16:39
  • 1
    Form1 form1 = new Form1(); This is most likely not the form you see on the screen. It's "new", and not "shown". Commented May 8, 2020 at 16:48
  • Possible duplicate of How to modify label text in form? Commented May 8, 2020 at 17:02

2 Answers 2

0

You instantiate MyNewClass in Form1, but in MyMethods() you create a new instance of MyNewClass and try to update the values the new instance.
One solution is to pass a reference of Form1 to MyMethods() like this:

public void MyMethods(Form1 form1)
{
 form1.MyTextBox.Text = "Salut toi";
}

And then in your Form1.cs, you write the following code:

 MyNewClass mnc = new MyNewClass();
 mnc.MyMethods(this);

You only have to make sure, that MyTextBox is not private. You can make it public by changing that in Form1.Designer.cs or using the designer and changing the property Modifiers to public.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you soooo much man !! I tried so solve it during a long time !
0

The methods in MyClass are creating a new Form1 and using it. They are not interacting with the instance of Form1 that is being shown on the sceen.

Here's a (not so great) text diagram of the information flow.

Form1 formOnScreen - - - >MyClass myClass - - - > Form1 newForm

What you want is for MyClass to call methods on the instance of Form1 that is on the screen. To do that, it needs a reference to that Form1. You can give it an instance of Form1 by passing it as a parameter in the methods you call on MyClass, by passing it to the constructor of MyForm and having it store the instance as a field, by creating a property on MyClass and setting it after creating an instance of MyClass, or any number of other ways.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.