Hey Guys,
I have a form setup as Form1.cs and I created a class named Database.cs. One of
my methods are trying to send an error to a text box in the form but I can reference
it. What code do I need to use to reference it?
Thanks,
Blake
Reference Form Control within Class
3 Answers
Know the answer? Post it. Somebody with the same question will find it here.

AlanRank #669 · 3.6K reputationPosted Nov 28, 2007, 1:58 PM EST
If you're using .NET 2.0 or later, then you can reference it like this:
Form1 form1 = (Form1)Application.OpenForms["Form1"];
form1.TextBox1.Text = "Some error message";
Your TextBox needs to be public for this to work.
Blake Arnold28 reputationPosted Nov 28, 2007, 2:14 PM EST
Thanks for the quick reply.
AlanRank #669 · 3.6K reputationPosted Nov 29, 2007, 12:06 AM EST
If both classes are defined within the same application, then they should be able to access each other whether they're declared public or internal (the default). You don't need any additional 'using' directives as the Application class is in the System.Windows.Forms namespace.
Also, Form1 (the startup form) must be in the OpenForms collection (at index zero) because, if it had somehow been closed, then the whole application would have terminated.
So, it's very puzzling that you can't access it. What error message are you getting?
There are, of course, other ways of getting a reference to Form1 such as passing it as a constructor argument when you instantiate your other class or exposing it as a public static property which is set in Form1's constructor.