Reputation: 3
I am trying to modify text on button(for example) in main form of my application.
But this thing does not work for the window which was created before Application.Run()
.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 Mainwindow = new Form1();
Application.Run(Mainwindow);
///Some stuff to do...
Mainwindow.button1.Text = "TextToChangeTo"; // And nothing happens here
}
Is there any nice workaround to be applied here?
Upvotes: 0
Views: 324
Reputation: 359
you should edit your code like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 frm = new Form1();
frm.button1.Text = "Some Text";
Application.Run(frm);
}
Upvotes: 0
Reputation: 12683
You are trying to set the button text in the main form after the Application.Run()
method. This is not correct as the text wont be set until after the application has finished.
Try adding the code to the constructor of the MainWindow() or in the load event. Example:
public partial class MainWindow : Form
{
public MainWindow()
{
InitializeComponent();
this.button1.Text = "Some Text";
}
}
Update
Display two possible solutions for manipulating controls on another form.
Passing the MainWindow
to another form.
Form2
public partial class Form2 : Form
{
MainWindow mainWindow;
public Form2()
{
InitializeComponent();
}
public Form2(MainWindow mainWndow)
:this()
{
this.mainWindow = mainWndow;
}
public void DoWork()
{
if (this.mainWindow != null)
this.mainWindow.button1.Text = "I set your text";
}
}
MainWindow
private void button1_Click(object sender, EventArgs e)
{
var form2 = new Form2(this);
form2.ShowDialog();
}
This example passes the instance of MainWindow
by using the this
keyword. In Form2
you will see the DoWork()
then can set the value.
Creating a static reference to MainWindow in your Program class.
Program.cs
static class Program
{
public static MainWindow MainWindow { get; private set; }
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Program.MainWindow = new MainWindow();
Application.Run(Program.MainWindow);
}
}
Form2.cs
public void DoWork()
{
Program.MainWindow.button1.Text = "I set your text";
}
Upvotes: 1
Reputation: 2171
If you add something after Application.Run(MainWindow)
it executes after MainWindow
close.
So add before it.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 Mainwindow = new Form1();
Mainwindow.button1.Text = "TextToChangeTo";
Application.Run(Mainwindow);
}
Upvotes: 0