Maayan Cahani
Maayan Cahani

Reputation: 121

Build a new class

I have simple Form1.cs which includes buttons, text boxes, etc. I would like to bulid a new class and to have the ability to call buttons and test boxes from Form1.cs

In the new class, when i type for example textbox. nothing appears. What is the easiest way to do this?

Thank you

Upvotes: 1

Views: 127

Answers (4)

Simon Price
Simon Price

Reputation: 3261

create a new instance of the class \ form

var myForm = new Form2()

then use myForm then call the control from this such as

    myForm.TextBox1.Text = "your text here"

Upvotes: 0

FlySoFast
FlySoFast

Reputation: 1932

You can pass the Form1 instance to the new class. The easiest way is to assign it at initialization. If you create the new class instance while in Form1, then use this:

In Form1:

NewClass nc= new NewClass(this);

With the new class looks like this:

public class NewClass
{
    Form1 fm;
    public NewClass(Form1 frm)
    {
        fm=frm;
    }

    void ChangeTextBox()
    {
         fm.YourTextBox.Text="Foo";
    }

}

Upvotes: 1

RePierre
RePierre

Reputation: 9576

You need to take several steps for this.

First of all, you need to expose the controls you want to access outside the form. To do so, in designer, select each control -> right-click -> Properties -> Modifiers -> change selection to Public;

Change control visibility.

Afterwards, in your class, create an instance of Form1 and access the controls you need:

var form = new Form1();
form.TextboxName.Text = "some text";

Upvotes: 0

Mohit S
Mohit S

Reputation: 14064

You should try

Form1.textbox

or

Form frm = new Form1();
frm.TextboxName

Where as to get the values of one form to another form you can also send it via objects. If you create the class of the values you are taking. and assign the values to the class members.

Upvotes: 0

Related Questions