0

I have a textbox in my main form.

Now I have created a function which is used to set the value of the text box.

public void SetTextOfTextBox(String text)
{
  textbox1.text = text;
}

Now in my main form I call another class (class b) which does some work for me. Now i want to be able to call my setTextofTextBox function from class b.

Now if I try Form1.SetTextOfTextBox("test"); this doesn't work. What am I doing wrong?

How do I access components of a a Form from another class.

Tomtom
  • 9,087
  • 7
  • 52
  • 95
Zapnologica
  • 22,170
  • 44
  • 158
  • 253

4 Answers4

2

Form1.SetTextOfTextBox("test"); this doesn't work

This doesn't work because SetTextOfTextBox is not static and you cannot access a non-static function directly. And you can't make it static either because your textbox is form level control.

How do I access components of a a Form from another class

You will have to pass the instance of Form1 to your other class to access it. Something like

  Class B = new ClassB(this);  //where this is the instance of Form1.
Ehsan
  • 31,833
  • 6
  • 56
  • 65
1

You will need a reference to the instance of Form1 in class b, otherwise you cannot call member methods.

Something like this:

class Form1 : System.Windows.Forms.Form {
    void functionInForm1() {
        ClassB objB = new ClassB();
        objB.doSomething(this);
    }
}

class ClassB {
    void doSomething(Form1 form) {
        form.SetTextOfTextBox("test");
    }   
}
Jeremy West
  • 11,495
  • 1
  • 18
  • 25
0

Find out the Form1 and call the method:

  foreach (var form in Application.OpenForms) {
    Form1 myForm = form as Form1;

    if (!Object.ReferenceEquals(null, myForm)) {
      myForm.SetTextOfTextBox("Test");

      break;
    }
  }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Did u try using delegates.

Specify the delegates in your ClassB like this.

public delegate void OnDone(string textValue);
public event OnDone OnUserDone;

after completing the task in ClassB call event:

OnUserDone("DoneClassB");

When u create the object of class in form map delegate function.

 Classb b=new Classb();
 b.OnUserDone += new Classb.OnUsrControlDone(CompletedClasss);

Define the function in form like below.

void CompletedClasss(string textValue)
{
            SetTextOfTextBox( textValue);
}
Praveen
  • 267
  • 1
  • 9