Reputation: 353
I have a windows forms app with a user control. I'm trying to get the UC to call a function on the main form, but when I add the UC, the main form can't see the public event.
My UC looks like this:
public partial class uctlLogin: UserControl
{
public delegate void ButtonClickedEventHandler(object sender, EventArgs e);
public event ButtonClickedEventHandler OnUserControlButtonClicked;
public uctlLogin()
{
InitializeComponent();
btnLogin.Click += new EventHandler(OnButtonClicked);
}
private void OnButtonClicked(object sender, EventArgs e)
{
if (OnUserControlButtonClicked != null)
OnUserControlButtonClicked(this, e);
}
}
My form code is:
public partial class frmMain : Form
{
UserControl uctlLogin1 = new TabletUserControls.uctlLogin();
public frmMain()
{
InitializeComponent();
uctlLogin1.OnUserControlButtonClicked += new EventHandler(OnUCButtonClicked);
}
private void OnUCButtonClicked(object sender, EventArgs e)
{
MessageBox.Show("Horray!");
}
private void frmMain_Load(object sender, EventArgs e)
{
this.Controls.Add(uctlLogin1);
}
}
The problem is in this line:
uctlLogin1.OnUserControlButtonClicked += new EventHandler(OnUCButtonClicked);
Generates the following message:
'System.Windows.Forms.UserControl' does not contain a definition for 'OnUserControlButtonClicked' and no extension method 'OnUserControlButtonClicked' accepting a first argument of type 'System.Windows.Forms.UserControl' could be found (are you missing a using directive or an assembly reference?)
I've tried putting the UC in the same project and creating the UC in a separate project, then adding a reference to it. After Googling for hours, I'm stuck. Any idea what I'm missing here?
BTW, I'm using VS2012 targeting the .Net Framework 4.5.
Upvotes: 0
Views: 662
Reputation: 292345
That's because in your frmMain
, you declared uctlLogin1
as UserControl
, rather than uctlLogin
. The type UserControl
doesn't have a OnUserControlButtonClicked
event, and the compiler doesn't know that uctlLogin1
is an instance of uctlLogin
, since you declared it as UserControl
. Just specify the actual type of uctlLogin1
and it will work fine.
Upvotes: 3