Kirsten
Kirsten

Reputation: 18066

Code Analysis gives "Declare event handlers correctly" message

I just ran code analysis on my c# winforms project. I get a warning

CA1009  Declare event handlers correctly    
Declare the second parameter of    'NameEditEx.TextChanged' as an EventArgs,
 or an instance of a type that extends EventArgs, named 'e'.     

The class in question is in a user control containing the following;

    public delegate void TextChanged();

    [Browsable(true)]
    public event TextChanged OnTextChanged;

A form that has the control on it has the following code in InitializeComponent

 this.nameEditEx1.OnTextChanged += new NameEditExLib.NameEditEx.TextChanged(this.nameEditEx1_OnTextChanged);

The method is

    private void nameEditEx1_OnTextChanged()
    {
        try
        {
            UpdateName();
        }
        catch (Exception ex)
        {
            HandleException.Show(ex);
        }

    }

The code appears to be working fine when I run it. Should I alter the code to get rid of the warning? If so, how do I do that?

Update Microsofts link

Upvotes: 2

Views: 5054

Answers (1)

Jeow Li Huan
Jeow Li Huan

Reputation: 3796

The delegate should be

public delegate void TextChanged(object sender, EventArgs e);

The method should be

private void nameEditEx1_OnTextChanged(object sender, EventArgs e)

Doing so ensures consistency for with other types of events where first argument is sender and second is EventArgs.

You can then invoke the event handler by calling

OnTextChanged(this, EventArgs.Empty);

Upvotes: 6

Related Questions