SupremeLeader
SupremeLeader

Reputation: 59

How to change the text from a textfield from a different class in WindowsForm

For a project I am trying to change the text of a RichTextBox using a method from a different class. However when trying to pass a string through, it doesn't change the text but when I write Console.Writeline, it does show up.

What I think the problem is, is that I have to refresh the WindowsForm before the text can change.

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

        private void button1_Click(object sender, EventArgs e)
        {
             addText.returnText();
         }

        public void addData(string s)
        {
            richTextBox1.AppendText(s);
            Console.WriteLine(s);
        }
    }
}

And the other class:

namespace RichTextBox
{
    class addText
    {
        public static void returnText()
        {
            string s = "test test;";
            Form1 f = new Form1();
            f.addData(s);
        }
    }
}

Upvotes: 1

Views: 42

Answers (2)

Abbas
Abbas

Reputation: 14432

Try debugging your code and you'll see that the text of the RichTextBox in the addText class is set. Only... it is another instance of Form1 and not your current shown form. Add following line in the returnText method to see this:

f.Show();

Pass the form as a parameter to the class and then this will work. In the button click event, change the line to following:

addText.returnText(this);

And the returnText method looks like this:

public static void returnText(Form1 form)
{
    string s = "test test;";
    form.addData(s);
}

But better would be to return a value from the class and set that value in the richtextbox in the form class:

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.AppendText(addText.returnText());
    // OR
    addData(addText.returnText());
}

public static string returnText()
{
    string s = "test test;";
    return s;
}

Upvotes: 2

NDJ
NDJ

Reputation: 5194

your returnText method is creating a new Form1, it shouldn't. There are a few options here, you could update the signature to expect a Form1 instance - returnText(Form1 f) and pass the current form instance to the method ( addText.returnText(this);

Or, and preferably, have the returnText method do exactly what it says - return the text, the calling code can update the rich text box. It keeps the responsibilities separate and clearer.

public static string returnText()
{
 string s = "test test;";
 return s;
}

calling code:

private void button1_Click(object sender, EventArgs e)
{
var s = addText.returnText();
addData(s);
}

Upvotes: 1

Related Questions