Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Winforms - Events

Status
Not open for further replies.

sand133

Programmer
Jun 26, 2004
103
GB
Hi, I have a basic form with a button and a usercontrol (which is just a label).
What I want to do is when I click the button, raise a custom event and have the usercontrol listen out for it.

Any ideas how i can do this? I have got as far as this.

The Event
---------


using System;
using System.Collections.Generic;
using System.Text;

namespace Events
{
public class myEvent: EventArgs
{
private string _name;


public myEvent(string name)
{
_name = name;
}

public string Name
{
get
{
return _name;
}
}
}
}



UserControl
------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace Events
{
public partial class myLabel : UserControl
{
public delegate void myEventHandler(Object sender, myEvent e);
public event myEventHandler someEvent;

public myLabel()
{
InitializeComponent();

this.someEvent += new myEventHandler(handleEvent);

}

void handleEvent(object sender, myEvent e)
{
MessageBox.Show("done");
}
}
}



THE FORM
---------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Events
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

}

private void simpleButton1_Click(object sender, EventArgs e)
{

}




}
}


 
It looks like your making this overly complicated. I would expose a public function on the user control and have the parent form call this public member directly.
Code:
public partial class MyUserControl : UserControl
{
   public void SetText(string textToDisplay)
   {
      myLabel.Text = textToDisplay;
   }
}

public partial class MyForm : Form
{
   protected Button_Click(object sender, EventArgs e)
   {
      string text = GetTextToDisplay();
      instanceOfMyUserControl.SetText(text);
   }
}

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hey Jason, thanks for your reply, I guess the solution you provided is ok for this situation or one where I dont have deep nested controls.
What if I have control A that needs to listen out for an event and control A is embedded in control B. How would I do this? Control B is on the form with a button that fires an event.

thanks

Sandip
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top