[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 327
  • Last Modified:

300 point EASY C# Question Get form field Value in different class

This has to be an easy question but i just cant find the answer.
I have a sample windows app in C#
namespace MyNameSpace
Formname = Form1
codebehind = Form1.cs
extra ClassName = Class1.cs

now Form1 has a textbox on it named Text1

and i want the value to be accessible in Class1

How would i go about it.  I tried making the textbox Public but i get an error about a static

Thanks

Steve
0
stevetheski
Asked:
stevetheski
  • 2
1 Solution
 
tomvergoteCommented:
what's the exact error or code?

it's kind of hard to guess what's going on at this point. either you are calling static stuff where you can't or something.
If you want to make variables available to other classes it's best to add a property for it.

public property myprop
{
   get{return myTextBox.Text}
}

or something along those lines.
0
 
stevetheskiAuthor Commented:
basically i dont get the intellisense option for TextBox1 when i am editing class1 when i type
MyNameSpace.Form1.
0
 
AaronReamsCommented:
You need to do two things here:

First you need to make the textbox public inside of your form class.  (This will make it show up in intellisense)

ex. public System.Windows.Forms.TextBox Text1;

The static error is probably because you are trying to access the textbox without having a reference to a Form1 object.  
(ex. Form1.Text1.Text will generate an error because there isn't an instance of the Form1 object)

You need to pass a reference of the form object to your class;

For example:

class Class1
{
    public Form1 myFormReference = null;
    public void AccessForm1TextBox()
    {
          if(myFormReference != null)
          {
                  myFormReference.Text1.Text = "Hello";
           }
     }
}

class Form1
{
     public System.Windows.Forms.TextBox Text1;
     public CreateClass1Object()
     {
           Class1 myClass1 = new Class1();
           myClass1.myFormReference = this;
           myClass1.AccessForm1TextBox();
     }      
}

Hope this helps clear things up.  Good luck -Aaron
0
 
AaronReamsCommented:
That should hopefully give you the basic idea.

Note:
"public CreateClass1Object()"  should be "public void CreateClass1Object()" in the Form1 class definition.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now