Link to home
Start Free TrialLog in
Avatar of Silas2
Silas2

asked on

Visual Studio C#, making events - coming from VB questions

I know there's a quick way to do this, but coming from  VB, say you have an object with events, you declare it WithEvents module level (I'm talking windows forms/silverlight), it gets listed in the LHS combo above the text window, you select it, then in the RHS combo, you get the events exposed by that object, you click on an event, and you get the stub, how do you do that in C#?
Avatar of p_davis
p_davis

open/pin the properties window --> select your object in the designer --> there is a lightning bolt icon at the top of the properties window -- these are your events for the currently selected object --> double click in the space next to the event you want and it will stub in the code for you.
suppose you have a class
public class MyObject
{
   //public fields
   public string myStringField;
   public int myIntField;
   public MyObject myObjectField;

   //public properties
   public string MyStringProperty { get; set; }
   public int MyIntProperty { get; set; }
   public MyObject MyObjectProperty { get; set; }

   //public events
   public event EventHandler MyEvent1;
   public event EventHandler MyEvent2;
}

The .NET class that gives us access to all of this is the Type class. To get a Type object, we simply use the typeof keyword:

Type myObjectType = typeof(MyObject);


To get a list of public fields in an object, we'll use Type's GetField method:

Type myObjectType = typeof(MyObject);

System.Reflection.FieldInfo[] fieldInfo = myObjectType.GetFields();

foreach (System.Reflection.FieldInfo info in fieldInfo)
combobox.items.add((info.Name));


you will list everything including events also
ASKER CERTIFIED SOLUTION
Avatar of Todd Gerbert
Todd Gerbert
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Silas2

ASKER

Sorry, I did meant to say 'object with no UI'. Doh - I should have checked the intelli sense.
There is no equivalent of WithEvents/Handles in C# so the two dropdowns across CODE editor screen are not present.

As the others have demonstrated, you either go back to the Form and use the events window in the Properties pane (exact same process as in VB), or manually wire up the vent via code.