0

Basically, I want to change a textbox's property inside class1, while class1 has an instance in that textbox's form. After my attempt a System.InvalidOperationException was thrown.

Would anyone help me?

public partial class mainForm : Form
{
    class1 c1;
    public mainForm() 
    {
        InitializeComponent();
        c1 = new class1(this);
    }
}

class class1
{
    mainForm mF;
    public class1(mainForm mF) 
    {
        this.mF = mF;
    }

    public void change()
    {
        mF.textBox1.Text = "Done!"; // I think the problem is here, but dunno why
    }
}

In addition, change() was called implicitly by c1(eg. not like c1.change()).But i call c1.general(), then c1.general() invoke c1.change().

Wai Lok Chan
  • 3
  • 1
  • 3
  • 1
    possible duplicate of [Referencing Windows Form elements in other classes](http://stackoverflow.com/questions/4099938/referencing-windows-form-elements-in-other-classes) - [How to access form methods and controls from a class in C#?](http://stackoverflow.com/questions/217389/how-to-access-form-methods-and-controls-from-a-class-in-c) – Prix Nov 12 '14 at 05:57
  • Use the debugger, Luke! – Uwe Keim Nov 12 '14 at 05:59
  • @Prix using property for textbox and void settextbox in mainForm didn't solve the 'InvalidOperationException' problem. – Wai Lok Chan Nov 12 '14 at 06:23
  • `InvalidOperationException` sounds suspiciously like the classic "cross-thread operation not valid" exception. Unfortunately, you haven't provided enough information -- both the full details of the exception, including stack trace, as well as a better code example -- but I'm guessing the `change()` method is getting called from a thread other than the one that owns your `Form` instance. – Peter Duniho Nov 12 '14 at 06:35
  • possible duplicate of [Winforms threading problem, second thread can't access 1st main forms controls](http://stackoverflow.com/questions/149394/winforms-threading-problem-second-thread-cant-access-1st-main-forms-controls) – Peter Duniho Nov 12 '14 at 06:39
  • @PeterDuniho If it is the case, what would you suggest me to debug? I am sorry that i didn't provide enough information because that's all i knew. Let me see your post first, thx a lot! – Wai Lok Chan Nov 12 '14 at 06:41
  • Check the link in my previous comment. If that doesn't answer your question, see http://stackoverflow.com/help/mcve for how to fix your question so that it can be answered. – Peter Duniho Nov 12 '14 at 06:47

0 Answers0