Hester Hester - 3 months ago 10
C# Question

Textbox not diplaying text

I am new to coding. I cannot figure out why my text box will not display text in windows forms using C#. Here is my code.

public partial class Form1
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

Form1 myTestObject = new Form1();
myTestObject.myTextPanel("hello");
}

public void myTextPanel(string myText)
{
// Windows Forms textBox1
textBox1.Text = myText;
}
}

Answer

You are running an instance of the Form1 and then create a new instance of the same( keep in mind both are different instance) and assigning values. you can Try this:

Form1 myTestObject = new Form1();
myTestObject.myTextPanel("hello");
Application.Run(myTestObject);

which will use the same instance of the Form1so you can see the text is appearing; you can make use of the constructor as well, instead for the myTextPanel method, the constructor will looks like the following:

public void Form1(string myText)
{
    // Windows Forms textBox1
    textBox1.Text = myText;
    // Do something
}

if so the main will changed as like the following:

Form1 myTestObject = new Form1("hello");  
Application.Run(myTestObject);

or like this :

Application.Run(new Form1("hello"));
Comments