Reputation: 165
I have a main Form with an event to open another Form.
Inside the first Form I define the event like this:
private void softToolStripMenuItem_Click(object sender, EventArgs e)
{
_frmSetting = new frmSetting();
_frmSetting.ShowDialog();
}
The event open a Form in the Dialog box. Everything is ok.
Inside the Form2 before the InitializeComponent();, I want to change the content of a TextBox on the Form 2.
So I do this this.textBox1.Text = "New text";
but it didn't work then I output to console:
this.textBox1.Text = "New text";
System.Console.WriteLine(this.textBox1.Text);
But this takes effect when immediately when the Form1 starts..I can see the console output. Normally the Console output were supposed to ve viewed only when I call Form2.
Does someone understand my needs?
EDIT
public form2()
{
InitializeComponent();
try
{
this.txtServer = new TextBox();
//this._parameter = new Parameter();
//this._get_parameter = new Dictionary<string, string>();
String _server_name;
//this._parameter.get_db_connection_parameters().TryGetValue("server", out _server_name);
this.txtServer.Text = _server_name.ToString();
System.Console.WriteLine(txtServer.Text + "---");
}
catch (Exception er) { System.Console.WriteLine("An error occurs :" + er.Message + " - " + er.StackTrace); }
}
Please don't bother about the commented lines, it works _server_name variable is getting its value from a text file and it works at this stage. The problem is around this line:
this.txtServer.Text = _server_name.ToString();
Upvotes: 0
Views: 113
Reputation: 165
Many thanks to all, everything works fine now. In fact, I was initialising Form2 in Form1() constructor and was getting this error Object reference to non object initialising (something like that). I move it here:
private void softToolStripMenuItem_Click(object sender, EventArgs e)
{
_frmSetting = new frmSetting();
_frmSetting.ShowDialog();
}
and now inside the Form2() after initializeComponent()
I just do this
this.txtServer = _server_name;
and it works
Upvotes: 0
Reputation: 43743
You're overcomplicating this. First, as others have said, you can't do it before the call to InitializeComponent
. Also, you don't need to create a new text box after the call to InitializeComponent
. Once that method has been called, the txtServer
text box will already be created and properly initialized. All you need to do then is set the value of its Text
property:
public form2()
{
InitializeComponent();
try
{
String _server_name;
// set value of _server_name
txtServer.Text = _server_name;
}
catch (Exception er) { System.Console.WriteLine("An error occurs :" + er.Message + " - " + er.StackTrace); }
}
Upvotes: 3
Reputation: 13033
You can't set any values to textbox before initializeComponent();
. If you look into initializeComponent function, you will see, that it does initialize all controls added in designer and your textbox as well.
You can't set the TextBox.Text property before initialisation, it will fail, that's it.
Upvotes: 0