Search code examples
c#event-handlingweb-user-controls

How do I register event handlers for a web user control in my code behind?


I'm having a problem setting up an event on a form. Here's the setup:

I was given a page with two controls, two different versions of a form for the end-user to fill out- standard and advanced. The two forms have different code and javascript, so the original dev put them in separate web user controls. Aside from the controls is a LinkButton that switches to Advanced mode.

<uc1:Standard runat="server" ID="StandardForm" />
<uc1:Advanced runat="server" ID="AdvancedForm" />
<asp:LinkButton runat="server" ID="lnkAdvanced" Text="Go To Advanced" OnClick="lnkAdvanced_Click" />

lnkAdvanced_Click just takes all the info currently entered to the advanced and flips the Visible.

My problem is that one of the bosses wants the 'Go to Advanced' button inside the standard form, but the .Visible code is on the page. So I thought it could be done using an event, but it doesn't seem to be working.

I tried to set up the event like this:

public event EventHandler AdvanceClick;

protected void lnkAdvanced_Click(object sender, EventArgs e) {
    AdvanceClick(sender, e);
}

And when that didn't work, I tried to set up a delegate:

public delegate void AdvancedEventHandler(object sender, EventArgs e);
public event AdvancedEventHandler AdvanceClick;

When I moved the button to the standard form, I expected to be able to type something like:

StandardForm.AdvanceClick += new AdvancedEventHandler(GoToAdvanced);

But it doesn't seem to recognize any events within the control! I get an error: "Standard does not contain a definition for 'AdvanceClick' and no extension method 'AdvanceClick accepting a first argument of type 'Standard' could be found" It finds the other properties just fine, am I going about this the wrong way?


Solution

  • If the standard form has the "Switch to advanced" button. Then, clearly, it has to know about the Advanced form and thus they seem to be pretty tightly coupled. If this is the case, it seems to me that you might as well just have the advanced form as a child of the standard form then... or better yet, merge them into one control.

    If you don't like these options you might want to create a third controls which hosts the button and the two forms, along with the logic to move data between them and toggle their visibility.

    I personally recommend the single control option. Having tighly coupled controls usually just leads to confusion down the road. You could loosen up the dependency in various ways, but think hard about it before you do so.

    In the legacy project I currently work on we have a bunch of examples such as serach forms and search results being split up into multiple controls, but then in the end needing each others instances to function properly. As I said earlier, I wont reccomend this path.