0

I'm wondering if it is possible to access a textbox value from another class inside a C# winform.

For example, at the moment I have a bunch of different textboxes I'm turning on and off all within my Form1.cs class like so:

   screentextBox.Visible = true;

However, to cut down on the amount of lines of code within my C# class I was wondering is it possible to make this call from another class, then in my Form1.cs call my other classes method?

Something like:

class Otherclass
{
   public void ShowTextBox()
   {
       screentextBox.Visible = true;
    }
}

Then in my Form1.cs simply call my new ShowTextBox method.

I'm sorry if this is a silly question, but I've looked around google and I couldn't find anything that could help me out.

N0xus
  • 2,674
  • 12
  • 65
  • 126
  • check out "Related" on the right hand side of the screen here: first post that I see is: http://stackoverflow.com/questions/217389/how-to-access-form-methods-and-controls-from-a-class-in-c?rq=1 – Wim Ombelets May 16 '13 at 08:59

8 Answers8

1

You could pass the TextBox as a parameter to a function in another class:

class OtherClass
{
    public void ShowTextBox(TextBox target)
    {
        target.Visible = true;
    }
}

However, I would advise to keep all the methods and code pertaining to handling the GUI and its events inside the form itself. If you have large methods for calculations, etc., than those can be moved to other classes.

John Willemse
  • 6,608
  • 7
  • 31
  • 45
0

you can Make ScreentextBox as Public in Declaring class and access it in Another class like

class Otherclass
{   
  public void ShowTextBox()
  {
      Class1.ScreenTextBox.Visible =true;
  }
}
Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83
0

You could define the ShowTextBox method in a partial class So you still have the access to the control and also tidy your code.

Bolu
  • 8,696
  • 4
  • 38
  • 70
0

Add method for showing TextBox in your form:

public partial class Form1 : Form
{
   public void ShowTextBox()
   {
       screentextBox.Visible = true;
    }
}

and then pass your From1 to other forms and call this method from there.

gzaxx
  • 17,312
  • 2
  • 36
  • 54
0
Class OtherClass
{
   public static void method(TextBox[] items)
   {
      foreach(item in items)
      {
         (item as TextBox).Visible = true;
      }  
   }
}

to call this method from ur Form1.cs class--->

OtherClass.method( new TextBox[] { TxtBox1, TxtBox2, TxtBox3 } );
Ashok Damani
  • 3,896
  • 4
  • 30
  • 48
0

If you want to access the controls of Form1.cs from another class try this way

class Otherclass
{
  Form1 f1 = new Form1();
  f1.Controls["screentextBox"].Visible = true;
}
anupama.kp
  • 56
  • 3
0

I would do it like this (example from John Willemse):

class OtherClass

{

    public TextBox ShowTextBox(TextBox target)
    {
       target.Visible = true;
       return target;
    }

}

gimpy
  • 54
  • 5
-1

Yet another approach to this old problem: I've found that the old way is an easy way to make accessible controls (including all their properties and methods), and perhaps other variables, from any class within the project. This old way consists of creating an ad hoc class from scratch.

Note A: about the old way: I know, I know, global variables are evil. But, for many people coming here looking for a fast/flexible/suites-most-cases solution, this may be a valid answer and I have not seen it posted. Another thing: this solution is what I am actually using as the answer for what I came to this page looking for.

1st step: The new class file from scratch is below.

namespace YourProjectNamespace
{
    public class dataGlobal
    {
        public System.Windows.Forms.TextBox txtConsole = null;

        // Place here some other things you might want to use globally, e.g.:
        public int auxInteger;
        public string auxMessage;
        public bool auxBinary;
        // etc.
    }
}

Note B: The class is not static nor has static members, which allows to create several instances in case it is needed. In my case I do take advantage of this feature. But, as a matter of fact, you may consider making this class' TextBox a public static field so that -once initialized- it is always the same throughout the application.

2nd step: Then you're able to initialize it in your Main Form:

namespace YourProjectNamespace
{
    public partial class Form1 : Form
    {
        //  Declare
        public static dataGlobal dataMain = new dataGlobal();

        public Form1()
        {
            InitializeComponent();

            // Initialize
            dataMain.txtConsole = textBox1;
        }
        // Your own Form1 code goes on...
    }
}

3rd step: And from your other class (or form), the call to any property/method of Form1's textBox1:

namespace YourProjectNamespace
{
    class SomeOtherClass
    {
        // Declare and Assign
        dataGlobal dataLocal = Form1.dataMain;

        public void SomethingToDo()
        {
            dataLocal.txtConsole.Visible = true;
            dataLocal.txtConsole.Text = "Typing some text into Form1's TextBox1" + "\r\n";
            dataLocal.txtConsole.AppendText("Adding text to Form1's TextBox1" + "\r\n");
            string retrieveTextBoxValue = dataLocal.txtConsole.Text;

            // Your own code continues...
        }
    }
}

[EDIT]:

A simpler approach, specifically for the TextBox visibility throughout classes, I have not seen in other answers:

1st step: Declare and initialize an auxiliary TextBox object in your Main Form:

namespace YourProjectNamespace
{
    public partial class Form1 : Form
    {
        //  Declare
        public static TextBox txtConsole;

        public Form1()
        {
            InitializeComponent();

            // Initialize
            txtConsole = textBox1;
        }
        // Your own Form1 code goes on...
    }
}

2nd step: And from your other class (or form), the call to any property/method of Form1's textBox1:

namespace YourProjectNamespace
{
    class SomeOtherClass
    {
        public void SomethingToDo()
        {
            Form1.txtConsole.Visible = true;
            Form1.txtConsole.Text = "Typing some text into Form1's TextBox1" + "\r\n";
            Form1.txtConsole.AppendText("Adding text to Form1's TextBox1" + "\r\n");
            string retrieveTextBoxValue = Form1.txtConsole.Text;

            // Your own code continues...
        }
    }
}

Comment to the [Edit]: I have noticed that many questions simply cannot be solved by the usual recommendation: "instead, make public properties on your form to get/set the values you are interested in". Sometimes there would be several properties/methods to implement... But, then again, I know... best practices should prevail :)

Alejandro QA
  • 334
  • 4
  • 9
  • IMHO this answer I have just posted applies as a solution to similar questions asked in this site. Following the advice of the elders I have chosen not to post it on other pages :) The recommendation is: http://meta.stackexchange.com/questions/104227/is-it-acceptable-to-add-a-duplicate-answer-to-several-questions The other pages that ask similar questions and that AFAICT cannot be merged are these: http://stackoverflow.com/questions/5646954/how-to-access-winform-textbox-control-from-another-class http://stackoverflow.com/questions/12157133/accessing-text-box-values-from-form-to-another-class – Alejandro QA Jun 02 '14 at 14:43
  • These are all *terrible* practices. You should not just be storing all of your information in global variables, rather class should be communicating with each other directly so as to keep the scope of data as small as is necessary, rather than making everything accessible everywhere in the application. This approach doesn't scale in the least, and very, very quickly results in entirely maintainable programs. It also doesn't ever support dealing with multiple instances of forms when everything is static, as the data isn't conceptually static. – Servy Jun 02 '14 at 15:44
  • Dear @Servy, please let me add this to your comment: I did emphasize in the post that "*I know, I know, global variables are evil*" and "*I know... best practices should prevail :)*". To code is a craftsmanship, and global variables, my friend, are my specialty :) – Alejandro QA Jun 03 '14 at 01:13
  • So you know that your answer is bad, you know that you shouldn't do it, but you choose to advocate that others use this really poor practice anyway, and don't have a problem with it? That's very unfortunate. – Servy Jun 03 '14 at 13:47
  • My friend: I don't agree with you, I don't think using a Global Variable is a bad practice *by default*. Sometimes it is useful and a better solution than others. But, then again, it is a matter of opinion. There are no stone-written rules about this, only recommendations and best practices suggestions. So again: I don't agree *my answer is bad*. You may not like it, but **it does the job**. I respect your preferences and suggestions regarding a better way to provide a solution to the question, even though I honestly don't agree with all of them. – Alejandro QA Jun 03 '14 at 14:26
  • I'm not saying it's always wrong to use public static variables. I'm saying it's wrong to use them *here*. The data isn't inherently static. It shouldn't inherently be accessible everywhere. It's not scalable or maintainable to make everything global like you have done. That you think it's a good idea is a pretty strong indication that you don't have a lot of experience in this regard. – Servy Jun 03 '14 at 14:36