click button on user control that will change text on parent form

  • Thread starter Thread starter thomasamillergoogle
  • Start date Start date
T

thomasamillergoogle

I have a simple problem I have a user control that I added to a main
form.

When I click a button in the user control I want to change the text of
a label that is in the main form.

This is the code in the user control:
private void button1_Click(object sender, System.EventArgs e)
{
Form1.ChangeIt();
}

this is the code in the main Form:

public static void ChangeIt()
{
//??????????????
//how to make this work using a static method?
this.label1.Text = "Clicked!!";
//??????????????

}
 
So you want the main Form to be notified when a Button in your UserControl
is clicked. Why not just create an event on your UserControl that the Form
can hook into? This event should be fired in response to the internal Button
being clicked.
 
In the usercontrol:
************************************

InitializeComponent or wherever the button is created:
this.button1.Click += new System.EventHandler(this.button1_Click);

private EventHandler buttonClick;
private void button1_Click(object sender, System.EventArgs e)
{
if (buttonClick != null)
buttonClick(sender, e);
}
public event EventHandler ButtonClicked
{
add { this.buttonClick += value; }
remove { this.buttonClick -= value; }
}




In the form:
*************************************
InitializeComponent or wherever the button is created:
this.userControl11.ButtonClicked += new
System.EventHandler(this.userControl11_ButtonClicked);

private void userControl11_ButtonClicked(object sender, System.EventArgs e)
{
this.label1.Text = "button clicked";
}


HTH;
Eric Cadwell
http://www.origincontrols.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top