Calling Windows Form Method from its User Control
I have a User Control on My windows Form, and there is a button on my 开发者_JAVA百科user control on click of which I want to call its form method.
Thanx
What worked for me is using delegate
public delegate void ClickMe (string message);
public partial class CustomControl : UserControl
{
public event ClickMe CustomControlClickMe;
public CustomControl()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (CustomControlClickMe != null)
CustomControlClickMe("Hello");
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
customControl1.CustomControlClickMe += new ClickMe(button2_Click);
}
void button2_Click(string message)
{
MessageBox.Show(message);
}
Provide your own public Click
event on your user control and subscribe to this event in the form that uses the control.
public class MyControl : UserControl
{
// ...
public event EventHandler Click;
// ...
}
Handle the button's click and then forward it to the public Click
event handler:
protected void button1_Click( object sender, EventArgs args )
{
var h = Click;
if ( h != null )
{
h( this, args );
}
}
If you only need to call methods provided by the Form interface you can simply call FindForm to retrieve the form that the control is on.
Form form = this.FindForm();
form.Close();
If the underlying Form is known you can do:
MyForm form = (MyForm)this.FindForm();
form.DoSomething();
Rethink your approach. If there is a cross-cutting conern that is shared by both the user control and the form, don't put the code for it on the form. By nature the user control can be shared across multiple forms, and there is no good reason why the user control should be tightly coupled to a specific form.
Move the code into a shared library/class and access it from the click even of the button on the user control. This way the user control won't care which form it is on.
That said, if you really need to access the user control from the form, pass an instance of the form into the control at runtime:
protected void Form_Load(object sender, EventArgse)
{
myUserControl.MainForm = this;
}
Then you can access public properties/methods on the MainForm from the usercontrol's MainForm
reference:
protected void MyButton_Click(object sender, EventArgs e)
{
MainForm.Foo();
}
Will call the Foo
method in the MainForm
instance.
(It has been a while since I did WinForms - so the method signatures for the event handlers might be slightly off, but the general principles should apply).
精彩评论