Can someone tell me what is wrong in my code? Try it with static and non-static event by commenting/uncommenting appropriate lines of code.
The name of project is "Try It" and this is main form:
Code
using System;Code
using System.Collections.Generic;Code
using System.ComponentModel;Code
using System.Data;Code
using System.Drawing;Code
using System.Linq;Code
using System.Text;Code
using System.Threading.Tasks;Code
using System.Windows.Forms;Code
namespace Try_ItCode
{C#
public delegate void dlgt_Delegate(); // This is delegate...Code
public partial class frm_Main : FormCode
{Code
//public static event dlgt_Delegate evnt_Event; //... and this should be static event.Code
public event dlgt_Delegate evnt_Event; //... and this should be non-static event.Code
public frm_Main()Code
{Code
InitializeComponent();Code
}Code
private void btn_Send_Event_Click(object sender, EventArgs e)Code
{Code
if (evnt_Event != null) // If someone is subscribed...Code
evnt_Event(); //... tell them.Code
}Code
private void btn_Exit_Click(object sender, EventArgs e)Code
{Code
this.Close();Code
}Code
}Code
}Code
This is my class which is added by Project->Add->Class:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Try_It
{
class cls_I_am_waiting
{
frm_Main Main = new frm_Main();
public cls_I_am_waiting() // This should be a constructor of a class,
{
//frm_Main.evnt_Event += frm_Main_evnt_Event; // I want to be notified when button is clicked on main form (static event)...
Main.evnt_Event += Main_evnt_Event; // I want to be notified when button is clicked on main form (non-static event)...
}
//void frm_Main_evnt_Event() //... with static event.
//{
// MessageBox.Show("O.K. I received it!"); //... and tell it!
//}
void Main_evnt_Event() //... with non-static event.
{
MessageBox.Show("O.K. I received it!"); //... and tell it!
}
}
}Thanks.

VulpesRank #55 · 29.2K reputationPosted Jul 22, 2014, 3:28 PM EDT
VulpesRank #55 · 29.2K reputationPosted Jul 22, 2014, 3:30 AM EDT
Peca5 reputationPosted Jul 22, 2014, 11:18 AM EDT
It works.
Can you explain to us this line of code:
new cls_I_am_waiting(this);
Also, I delete from code marked lines an everything works fine:
{
---> frm_Main Main = null; <--- deleted...
...and change from (frm_main main) to (frm_main Main)...
public cls_I_am_waiting(frm_main Main) // This should be a constructor of a class,
{
---> Main = main; <---- ... deleted
//frm_Main.evnt_Event += frm_Main_evnt_Event; // I want to be notified when button is clicked on main form (static event)...
Main.evnt_Event()...
Peca5 reputationPosted Jul 22, 2014, 10:34 PM EDT