yrazlik
yrazlik

Reputation: 10777

How to access GUI elements from a class in C#?

I have windows application in C# and have a richtextbox in the GUI. I want to reach the richtextbox and append some text to it from inside a class. I thought about creating a static RichTextBox item in the form's code file and then call it like this:

public partial class Form1 : Form
{
    public static RichTextBox box;

    public Form1()
    {
        box = richtextbox_in_gui;
    }
}

public class SomeClass()
{
    Form1.box.AppendText("...");
}

Is that a safe way to do it? Or is there any other way i can do this?

Thanks

Upvotes: 1

Views: 5143

Answers (1)

Femaref
Femaref

Reputation: 61437

You don't want a static field, as that would be for all instances of Form1; it should be a normal field.

However, public fields are not a good idea, as the class can be manipulated from the outside. You'll want to encapsulate the behaviour, so the best idea is a method:

public partial class Form1 : Form
{
    public Form1()
    {
        box = richtextbox_in_gui;
    }

    public void AppendText(string text)
    {
      this.textbox.AppendText(text);
    }
}

public class SomeClass
{
  private Form1 form;

  public SomeClass(Form1 form)
  {
    this.form = form;
  }

  public void AppendHelloWorld()
  {
    this.form.AppendText("Hello World");
  }
}

Now, if you have a reference to the form object, you can use the AppendText method:

Form1 form = new Form1();
var some = new SomeClass(form);
some.AppendHelloWorld();

This style of coding is called Dependency Injection.

Upvotes: 4

Related Questions