There was a problem. Created a Windows application in C #. The form is, for example, a textbox. In the Program.cs file, I created several of my own classes, but when I try to access textbox, this cannot be done (as if it does not exist). I tried to transfer the class hierarchy to the Form1 class from Form1.cs - now it can be selected by TextBox, writes that it cannot acces to non-static member, etc. etc.

How can I access the textbox, preferably several options and how best.


    3 answers 3

    Your textbox is a member of the Form1 class, access to it is possible inside the member functions of the Form1 class,


     namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void DoSomeStuffWithTextBox() { textBox1.Text = "some text"; } } } 

    And on the class object through a point from other classes - is impossible, since the access level of textboxes inserted through the form designer is private


     namespace WindowsFormsApplication1 { partial class Form1 { ................................ private System.Windows.Forms.TextBox textBox1; } } 

    Although, you can manually change the access level for textBox1 to public in this file;) <crutch />. And, although the file is generated automatically, if you change the form, your editing will be saved (if you do not delete textBox1 from the form, of course).

    It is best to make a public method (or property) in the form that returns a reference to textBox1 .

     namespace WindowsFormsApplication1 { public partial class Form1 : Form { ..................... public TextBox getTextBox() { return textBox1; } } } 
    • Thanks for an exhaustive explanation) - Programmer
    • and how to call getTextBox () from another class? - Julian Del Campo

    As far as I remember, you can still click on TextBox in the designer and change the access method to public in Properties.

    • This is not an answer, but a comment to the answer. Yapycoder - Pavel Mayorov

    Can do so

      Form1 childForm = new Form1(); // класс Form1 должен быть public childForm.textBox1; 

    At the same time, make the textBox1 public access type as written by ArtFeel or in the Form1.Designer class Form1.Designer find your text box and set the access type instead of private - public

     public System.Windows.Forms.TextBox textBox1;