Hey all,
Just a quick one for you.
How can i create an instance of a form from within a method? I know in the code below i can put the Form2 bob = new Form2(); within the public partial class Form1 : Form block it will work. But i dont want to create the instance of Form2 untill the button is clicked.
I thought i might be able to create a makeform() method then create the form in there. But i couldnt get it to work.
See code below:
using System;
using
System.Collections.Generic;using
System.ComponentModel;using
System.Data;using
System.Drawing;using
System.Linq;using
System.Text;using
System.Windows.Forms;namespace
WindowsFormsApplication1{
public partial class Form1 : Form{
public Form1(){
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
Form2 bob = new Form2();bob.textBox1.text =
"Hello";}
private void button2_Click(object sender, EventArgs e){
button1_Click.bob.textBox1.text =
"Hello Again"; // I know this will not work.}
}
}
Thanks in advance,
James
JamesPosted Jul 23, 2008, 8:02 PM
Satish KathiPosted Jul 23, 2008, 1:15 PM
Create a private variable of Form2 at the class level, so you can access that any where with in the class. look for the changes in bold font. Now when you create an object in button click you can assign value to the text box in form2, make sure accessiblity of the text box is public. Is this waht you are looking for?
using System;
using System.Collections.Generic;
using
System.ComponentModel;using
System.Data;using
System.Drawing;using
System.Linq;using
System.Text;using
System.Windows.Forms;namespace
WindowsFormsApplication1{
public partial class Form1 : Form
{
Form2 bob;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bob = new Form2();
bob.textBox1.text = "Hello";
}
private void button2_Click(object sender, EventArgs e)
{
bob.textBox1.text = "Hello Again";
}
}
}