dotnetnoob
dotnetnoob

Reputation: 11330

Declaring multiple event handlers does not work

I have a page that can contain multiple user controls. Each user control has at least one button that invokes an event. I want to capture these events.

I produced a test page - the results are that a single handler explicity set on the user control works, however a ForEach does not. Here's the code:

    protected void Page_Load(object sender, EventArgs e)
    {
        // This works
        JumpButton1.HasVisited += new EventHandler(JumpButton_HasVisited);

        // This does not work            
        this.Controls.OfType<JumpButton>()
        .ForEach(uc => uc.HasVisited += new EventHandler(JumpButton_HasVisited));
    }

    void JumpButton_HasVisited(object sender, EventArgs e)
    {
        Label1.Text = "Updated button: " + DateTime.Now;
    }

For information when I count the controls returned - a count of 1 is returned which would indicate that the controls are being found.

Any ideas where I might be going wrong?


UPDATE 1

Here is an example using my own extension method to find the controls. I added a check to see if jumGroup contained any controls, and it does. However the handler still does not trigger.

        var jumpGroup = Page.FindControls<JumpButton>();
        foreach (var item in jumpGroup)
        {
            // This shows ID's
            Response.Write(item.ID);
        }

        jumpGroup.ForEach(uc => uc.HasVisited += new EventHandler(JumpGroup_HasVisited));

UPDATE 2

Tracked the source of the problem but stil not sure why this doesn't work. IEnumerable extension method is at fault - when replaced by a foreach loop this works.

    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> @this, Action<T> action)
    {
        @this.ThrowNull("@this");
        action.ThrowNull("action");

        foreach (T item in @this)
        {
            action(item);
            yield return item;
        }
    }

Upvotes: 1

Views: 184

Answers (1)

dotnetnoob
dotnetnoob

Reputation: 11330

The actual issue related to the IEnumerable.ForEach() extension method being used, which did not carry out the actions. Having amended the extension method, the code above now works.

Upvotes: 1

Related Questions