0

I am trying to create GUI using C# windows form applications. I have written one method in the mainfrom. I have two check boxes in one of the user controls. when check box changed then i need to raise that event in the main form and run the method which i have written in mainfrom, in that event. How can i do this ?.

Gajendra
  • 1,291
  • 1
  • 19
  • 32
reddy
  • 183
  • 4
  • 15

4 Answers4

0

Look up delegates in the help. You create an procedure in the main box, a delegate in the control, set the delegate to the procedure in the main procedure and call the in checkbox.checked.

One work of warning - put a check in that the delegate is not null (meaning it wasn't set) otherwise you'll get an error.

Jeff B
  • 535
  • 1
  • 6
  • 15
0
public class MainForm : Form
{
    public void YourMethod()
    {
        ///
    }
}

public class UserControl
{
    private readonly MainForm _MainForm;

    public UserControl(MainForm mainForm)
    {
        _MainForm = mainForm;

        ///add event for checkbox
    }

    private void Checkbox_Clicked(object Sender, EventArgs e)
    {
        _MainForm.YourMethod();
    }

}
0

In your user control do the following (example from my own custom control i made, adjust it to what you need obviously :)):

public event EventHandler InnerDiagramCheckBox1CheckChanged;

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if (InnerDiagramCheckBox1CheckChanged != null)
    {
        InnerDiagramCheckBox1CheckChanged(sender, e);
    }
}

Then what you can do in the main form on its load or construct is:

instanceofyourcontrol.InnerDiagramCheckBox1CheckChanged+= new 
System.EventHandler(nameofthefunctionyouwanttotriggerinthemainform);

What you do here is delegating the events to your user control :)

Ken de Jong
  • 219
  • 1
  • 11
  • I have tried your method but i am getting errors in the mainfrom load when i use the above code like "usercontrol.InnerDiagramCheckBox1CheckChanged" is a field but used like a type. – reddy Apr 12 '13 at 13:42
0

Create a delegate in user control and make it to point the function in main form. Create OnCheckedChanged() event for the checkboxes in usercontrol and call the delegate method in the event.

Look into this example

mainform.cs

mainform_load()
{
// Initialize user control delegate object to point the method in mainform
usercontrol1.method= Method1;
...
}

// method to call from usercontrol
public void Method1()
{

}

usercontrol1.cs

delegate void Method1()
public PointMyMethod method;

...

checkbox1_OnCheckedChanged()
{
    // This calls the method in mainform
    method();
}

...

Hope it helps

SMS
  • 452
  • 2
  • 6