I have a User Control UC1
which consists of one button clickMeButton
. I want to add this User Control to my main form Form1
, and when I click on clickMeButton
I want another button changeButton
in the form to change text. However, nothing happens. I know there are several posts about this and I have read them but it doesn't solve my issue. Here is my code:
User control class:
public partial class UC1: UserControl
{
public event EventHandler ClickHereButtonClicked;
public UC1()
{
InitializeComponent();
}
private void OnButtonClick(object sender, EventArgs e)
{
ClickHereButtonClicked?.Invoke(this, e);
}
}
Form:
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
uC11.ClickHereButtonClicked += new EventHandler(ButtonClick_Handler);
}
private void ButtonClick_Handler(object sender, EventArgs e)
{
changeButton.Text = "Button clicked!";
}
}
The User Control uC11
and changeButton
are declared in the Form1.Designer
class. I use Visual Studio.
I have a User Control UC1
which consists of one button clickMeButton
. I want to add this User Control to my main form Form1
, and when I click on clickMeButton
I want another button changeButton
in the form to change text. However, nothing happens. I know there are several posts about this and I have read them but it doesn't solve my issue. Here is my code:
User control class:
public partial class UC1: UserControl
{
public event EventHandler ClickHereButtonClicked;
public UC1()
{
InitializeComponent();
}
private void OnButtonClick(object sender, EventArgs e)
{
ClickHereButtonClicked?.Invoke(this, e);
}
}
Form:
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
uC11.ClickHereButtonClicked += new EventHandler(ButtonClick_Handler);
}
private void ButtonClick_Handler(object sender, EventArgs e)
{
changeButton.Text = "Button clicked!";
}
}
The User Control uC11
and changeButton
are declared in the Form1.Designer
class. I use Visual Studio.
1 Answer
Reset to default 0As others have stated, it's possible that you don't have the OnButtonClick
method wired up to the button in your usercontrol.
Change:
public UC1()
{
InitializeComponent();
}
To:
public UC1()
{
InitializeComponent();
clickMeButton.Click += new EventHandler(OnButtonClick);
}
OnButtonClick
because it has unusual name for button event handler. – Sinatr Commented Mar 21 at 15:53OnButtonClick
. To change text ofchangeButton
someone should callOnButtonClick
first. As I say previously the name is unusual, I suspect it's not event handler generated by designer, but maybe a custom method and noone is calling it. You can include designer-generated code (content of all*.Designer.cs
files) to let us check it. – Sinatr Commented Mar 21 at 16:34