troubleshooting Question

Late binding to an event - please provide source code solution, no links.

Avatar of Tom Knowlton
Tom KnowltonFlag for United States of America asked on
C#ASP.NET
61 Comments2 Solutions630 ViewsLast Modified:
I have some dynamic controls that I am loading in at runtime.  These controls have events they can raise, which I will NOT know about ahead of time, but I will have methods with matching signatures.  What I want to accomplish is to tie those events to the handlers.

Look for my comments in the code below to see what method I want to attach to.  I don't want to FIRE the event...I just want to become a listener.


When you reply...please provide working C# source code ONLY!!   Please....NO LINKS TO ARTICLES OR WEBSITES!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Reflection;

namespace Campus_Webstore
{
    public partial class SiteManager : System.Web.UI.Page
    {
        protected void Page_PreInit(object sender, System.EventArgs e)
        {
            this.MasterPageFile = "~/contentfiles/" + Page.StyleSheetTheme + "/TCSSite.Master";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GlobalMethods.InitControlList();


                string layout = "";

                if (Request.QueryString["layout"] != null)
                {
                    layout = Request.QueryString["layout"] as string;
                }
                else
                {
                    layout = "default";
                }

                DisplayLayout(layout);

            }
           
        }

        private void DisplayLayout(string layout)
        {
            GlobalMethods.divlayoutgencontrols.Clear();

            StreamReader sr = new StreamReader(Server.MapPath("~/CustomLayouts/") + Page.StyleSheetTheme + "/" + layout + ".xml");
            string filecontents = sr.ReadToEnd();
            string countstr = GlobalMethods.ExtractValueFromXML(filecontents, "<count>");
            int count = Convert.ToInt32(countstr);
            string tempGUID = "";
            string settings = "";
            string[] settingsarray = new string[count];

            for (int i = 1; i <= count; i++)
            {
                settings = GlobalMethods.ExtractValueFromXML(filecontents, "<" + i.ToString() + ">");
                settingsarray = settings.Split(',');

                Control c = LoadControl("~/UserControls/" + settingsarray[0] + ".ascx");

                Type controlType = c.GetType();
                BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public;
                EventInfo[] myEvents = controlType.GetEvents(myBindingFlags);

                for(int j = 0; j < myEvents.Count(); j++)
                {
                    string eventName = myEvents.ElementAt(j).Name;
                    if (eventName == "NameAvailabilityEvent")
                    {
                        //Delegate d = Delegate.CreateDelegate(myEvents.ElementAt(j).EventHandlerType, this,myEvents.ElementAt(j).Name);
                        //c.GetType().GetEvent(eventName).AddEventHandler(c, d);






                        //btn is "c"

                        EventInfo evt = c.GetType().GetEvent(myEvents.ElementAt(j).Name);
                        MethodInfo handler = GetType().GetMethod("SomeHandler");




//////////////////////////////   HERE IS WHERE THE BINDING MIGHT TAKE PLACE  /////////////////////////////////





                        evt.AddEventHandler(c, Delegate.CreateDelegate(
                                evt.EventHandlerType, this, handler));

                    }
                }              

                c.Visible = true;
                tempGUID = Guid.NewGuid().ToString();
                c.ID = settingsarray[0] + tempGUID + i.ToString();

                GlobalMethods.divlayoutgencontrols.Add(c);
            }

            foreach (Control c in GlobalMethods.divlayoutgencontrols)
            {
                sitemanagercontrolsdiv.Controls.Add(c);
            }


            Master.CalcCartTotal();
            Master.ShowCat();
            Master.DisplayUser();

        }



////////////////////   I WANT TO BIND THE EVENT TO THIS METHOD  /////////////////////////////////////////

        public void SomeHandler(bool wasavailable)
        {
       //     create_new_user.ShowRotatingArrow(true);

            if (wasavailable)
            {
                //LabelResultMessage.Text = "That username is available.";
                //ButtonClosePanelMessage.Visible = true;
                //PanelMessage.Visible = true;
            }
            else
            {
                //LabelResultMessage.Text = "That username is already taken.";
                //ButtonClosePanelMessage.Visible = true;
                //PanelMessage.Visible = true;

            }

          //  create_new_user.ShowRotatingArrow(false);
        }
    }
}
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 2 Answers and 61 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 61 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros