I want to cath an event thrown by the class "Class1" in the class "Form1" to display data in the textbox1. Even though the code pass by the eventhandler, as a messageBox pop-up, can someone tell me why I can't see the text "connected!", in the textbox1?
Thanks.
namespace WindowsFormsApplication1
{
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
namespace WindowsFormsApplication1
{
class Class1
{
public delegate void Connected_EventHandler();
public static event Connected_EventHandler OnConnected;
public void connect()
{
Form1 f = new Form1();
OnConnected += new Connected_EventHandler(f.onConnectedEventHandler);
DoSomething();
}
private void DoSomething()
{
if (OnConnected != null)
{
OnConnected();
}
}
}
}
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Class1 cl = new Class1();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
cl.connect();
// textBox1.Text = "connected!"; If I uncomment this line, the textbox display the text
}
public void onConnectedEventHandler()
{
//MessageBox.Show("HELLO"); If I uncomment this line, the message pop-up
textBox1.Text = "connected!"; // The textbox doesn't display the data!
}
}
}
Carl SchraderPosted Jan 11, 2009, 2:59 PM
Wone,
It's because your obtaining a reference to a different Form object (not the form object currently being displayed) when the following lines execute:
Do this insead:
namespace
WindowsFormsApplication1{
public partial class Form1 : Form{
Class1 cl = new Class1(); public Form1(){
InitializeComponent();
Class1.OnConnected += new Class1.Connected_EventHandler(onConnectedEventHandler);}
private void button1_Click(object sender, EventArgs e){
cl.connect();
// textBox1.Text = "connected!"; If I uncomment this line, the textbox display the text}
public void onConnectedEventHandler(){
//MessageBox.Show("HELLO"); If I uncomment this line, the message pop-uptextBox1.Text =
"connected!"; // The textbox doesn't display the data!}
}
class Class1{
public delegate void Connected_EventHandler(); public static event Connected_EventHandler OnConnected; public void connect(){
DoSomething();
}
private void DoSomething(){
if (OnConnected != null){
OnConnected();
}
}
}
}
Carl
wonePosted Jan 11, 2009, 3:53 PM
Kay