Click here to Skip to main content
15,896,912 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

Can we pass an additional parameter to an event handler method.
I have a panel in my form and i want to paint it with gradient colors on its paint event.
The Colors will be conditional and based on some value. Can i directly pass this value to the paint event.
I don't want to use global variable or property.
Is there any option?
Posted

1 solution

Not to "event", but to an event handler.

Parameters of the even handlers are defined by the "event arguments" class (derived from System.EventArgs); and you cannot change the signature of the event handler. So, you should have asked, "can I pass additional information?". Of course you can.

(If it was the event you define yourself, you would need to create you own event arguments class where you would put all the information you need. In your case of Paint event, this is not an option.)

You can implement rendering on one of two ways: 1) overriding Control.OnPaint; 2) handling the event .Control.Paint. The signatures of these methods are:
C#
protected override void OnPaint(PaintEventArgs e) { /* ... */ }

//...

// alternatively, an event handler:
void SomeEventHandlerOfThePaintEvent(object sender, PaintEventArgs e) { /* ... */ }

How many parameters are there? The answer 1 and 2 would be wrong. Actually, it's 2 and 3. There is one more hidden argument: "this", because first method is the instance (non-static) method; and any event handler can be instance one. You can use "this" to pass any additional information (and this is the very basic element of the beginners of OOP, not even using the heart of OOP: late binding):
C#
using System.Windows.Forms;
using System.Drawing;
//...

class SomeControl : Control {

    Color someGradientColor;
    Color CalculteAnotherGradientColor() { /* ... */ }

    protected override void OnPaint(PaintEventArgs e) {
        // use someGradientColor here
        // ...
        Color someColorToRender = CalculteAnotherGradientColor();
        // and so on...
        // for further detail, please see my past answers referenced below
    }

} //class SomeControl


Something like that.

Please see also my past answers:

Static vs instance methods:
Type casting in c#[^],
C# windows base this key word related and its uses in the application[^],
What makes static methods accessible?[^];
Rendering graphics with passing data:
What kind of playful method is Paint? (DataGridViewImageCell.Paint(...))[^],
capture the drawing on a panel[^],
Drawing Lines between mdi child forms[^],
How to speed up my vb.net application?[^],
Zoom image in C# .net mouse wheel[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900