Link to home
Start Free TrialLog in
Avatar of deleyd
deleydFlag for United States of America

asked on

Calling Method in another class

AppendTextBox1 is defined in my Form1 class. How can I call it from another class to append text to my TextBox1?

using System;

namespace Program
{
  class MyClass
  {
    public MyClass()
    {
      AppendTextBox1("Hello World from MyClass" + Environment.NewLine);
    }
  }
}

Open in new window


using System;
using System.Windows.Forms;

namespace Program
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    // This delegate enables asynchronous calls for setting
    // the text property on the textBox1 control.
    delegate void AppendTextBox1Delegate(string text);


    /* Call this method to append text to textBox1 */
    public void AppendTextBox1(string text)
    {
      if (this.textBox1.InvokeRequired)
      {
        AppendTextBox1Delegate d = new AppendTextBox1Delegate(AppendTextBox1);
        this.textBox1.Invoke(d, new object[] { text });
      }
      else
      {
        this.textBox1.AppendText(text);
      }
    }


    private void button1_Click(object sender, EventArgs e)
    {
      AppendTextBox1("Hello World from button1_Click" + Environment.NewLine);
      MyClass m = new MyClass();   //test
    }
  }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial