Shen
Shen

Reputation: 644

How to find the control that raised an event

I have many custom controls on my main form that utilize an event to signify they have done processing. They all share this same event (~100 controls or so).

The main form consumes this event but I do not have a clue how to find an efficient way at getting to the one that raised the event without having really inefficient code.

My controls are contained within a List<T> called controlList and are hosted on their own project.

My event looks like so:

public void OnTaskComplete(object sender, custom_control_project.TaskCompleteEventArgs e)
    {
        foreach (var control in controlList)
        {
            if (control.Visible) // <--- THIS IS WRONG! WHAT COULD THIS BE???
            {
                try
                {
                    ...// LOTS OF PROCESSING!
                }
                catch
                {
                    ...
                }
                finally
                {
                    ...
                }
            }
        }        
    }

If I want to use less controls, I make them invisible and disabled, hence the control.Visible.

How can I make it so I only do work on the one control that raised the event without having to process so much unneeded iterations?

Upvotes: 0

Views: 160

Answers (2)

andleer
andleer

Reputation: 22578

Assuming the all of the controls are wired to the same event (which you indicate):

protected void Button1_Click(object sender, EventArgs e)
{
    ((Button)sender).Visible = true;

    // or more generally:
    ((WebControl)sender).Visible = true;
}

You will need to cast the sender to a common, base type. If you go with a base type, WebControl will allow you to access the Enabled property while Control will not.

Upvotes: 1

Dom
Dom

Reputation: 716

The sender parameter is the object that raised the event. You can cast this to a control.

Upvotes: 8

Related Questions