473,473 Members | 1,637 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to pass more than two parameters in the event handler

Can anyone suggest me to pass more parameters other than two parameter for
events like the following?

Event:
Onbutton_click(object sender, EventArgs e)"

Event handler:
button.Click += new EventHandler(Onbutton_click);

I want to pass more information related that event. & want to use that
information in the event.
Jul 17 '08 #1
24 54993
Swappy <Sw****@discussions.microsoft.comwrote:
Can anyone suggest me to pass more parameters other than two parameter for
events like the following?

Event:
Onbutton_click(object sender, EventArgs e)"

Event handler:
button.Click += new EventHandler(Onbutton_click);

I want to pass more information related that event. & want to use that
information in the event.
The normal way of passing more information is to make a richer type
derived from EventHandler.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jul 17 '08 #2
On Wed, 16 Jul 2008 22:47:01 -0700, Swappy
<Sw****@discussions.microsoft.comwrote:
Can anyone suggest me to pass more parameters other than two parameter
for
events like the following?

Event:
Onbutton_click(object sender, EventArgs e)"

Event handler:
button.Click += new EventHandler(Onbutton_click);
Minor nit: I think you have your labels reversed. :) The "Event" is
"button.Click" and the "Event handler" is the method itself.
I want to pass more information related that event. & want to use that
information in the event.
What kind of information? Where would it come from?

The usual approach is to use an anonymous method with an event handler
that has your modified signature. For example:

void Onbutton_click(object sender, EventArgs e, int i) { ... }

button.Click += delegate(object sender, EventArgs e)
{ Onbutton_click(sender, e, 172); };

Of course, you don't have to pass in 172, or even make the third parameter
an int. :)

But whether that works depends on what information you're trying to pass..
If the above example doesn't lead to an immediate solution for you, you
might want to provide more details as to what you're actually trying to do.

Pete
Jul 17 '08 #3
Hey,
Jon Skeet is right with his suggestion about deriving from event args and
making you own delegate for the event. That is the standard way .NET does it
and there is necessarily anything wrong with it.
There is a bit of debate about it though as some people suggest that it is
not ideal to parse a reference to the sender and an EventArgs derived class
to a set of event handlers that only need to know a boolean or and int. They
believe that having lots of derivations of EventArgs introduces unnecessary
code bloat and is a waste of time.
I am personally undecided on the matter as although I like the idea of
having a standard 'look' for events, I also agree with the simplicity of just
parsing the needed data for events. The only down side of this is if you do
decide in the future to add a second piece of data, you need to change the
event and therefore all the subscribers. EventArgs does get round that for
you. For futher information on this argument and events in general, there was
recently a dotnetrocks episode on them:
http://www.dotnetrocks.com/default.aspx?showNum=355

I will leave it to you to come up with the solution yourself. Just thought I
would make you aware of the two sides to the debate.
--
Ciaran O''Donnell
http://wannabedeveloper.spaces.live.com
"Swappy" wrote:
Can anyone suggest me to pass more parameters other than two parameter for
events like the following?

Event:
Onbutton_click(object sender, EventArgs e)"

Event handler:
button.Click += new EventHandler(Onbutton_click);

I want to pass more information related that event. & want to use that
information in the event.
Jul 17 '08 #4
On Jul 16, 10:47*pm, Swappy <Swa...@discussions.microsoft.comwrote:

Hey Swappy, I see three MVP's (Peter is also an MVP but he doesn't
like to talk about it) have answered your question, so far be it for
me to add my 0.02 dollars, but I would say that you should think twice
about passing parameters through Events other than as provided by
MSFT's wizards. Rule of thumb: don't mess with wizard generated
code, ever.

So I guess (if I read correctly) that I'm with Ciaran when he said:
"there is a bit of debate about it though as some people suggest that
it is not ideal to parse a reference to the sender and an EventArgs
derived class
to a set of event handlers that only need to know a boolean or and
int. They believe that having lots of derivations of EventArgs
introduces unnecessary code bloat and is a waste of time". Plus it's
dangerous--you mess up the library you have to reinstall Visual Studio
and that takes several hours.

So, I would set up a user defined "Event" using a publisher-subscriber
model--I posted recently in this forum an excellent console mode
example of this--rather than using the Event handler stuff generated
by the code wizard.

RL

( a newbie with a good month's worth--but a solid month--of C#
experience)
Jul 17 '08 #5
On Jul 17, 8:05 am, raylopez99 <raylope...@yahoo.comwrote:
On Jul 16, 10:47 pm, Swappy <Swa...@discussions.microsoft.comwrote:
int. They believe that having lots of derivations of EventArgs
introduces unnecessary code bloat and is a waste of time". Plus it's
dangerous--you mess up the library you have to reinstall Visual Studio
and that takes several hours.
I'm curious, how could deriving your own class from EventArgs possibly
"mess up the library" causing you to have to re-install VS?

Chris
Jul 17 '08 #6
Comments:
Hey Swappy, I see three MVP's (Peter is also an MVP but he doesn't
like to talk about it) have answered your question, so far be it for
me to add my 0.02 dollars,
errrrm.
I am NOT an MVP, and according to the Microsoft MVP awardies page, Peter
Duniho is not a current MVP holder
(https://mvp.support.microsoft.com/co...=peter+duniho).
but I would say that you should think twice
about passing parameters through Events other than as provided by
MSFT's wizards. Rule of thumb: don't mess with wizard generated
code, ever.
Events in .NET are not normally generated by wizards. They are made with
code like:
public delegate void MyEventHandler(object sender, MyEventEventArgs e);
public event MyEventHandler MyEvent;
There is nothing autogenerated about the above code. It is just C# written
by hand in this windows to create an delegate type, and an event.
>
So I guess (if I read correctly) that I'm with Ciaran when he said:
"there is a bit of debate about it though as some people suggest that
it is not ideal to parse a reference to the sender and an EventArgs
derived class
to a set of event handlers that only need to know a boolean or and
int. They believe that having lots of derivations of EventArgs
introduces unnecessary code bloat and is a waste of time".
This was a point of view that I raised as Devils Advocate rather than
voicing me own opinion. I tend to think of the phrase "Horses for courses",
as in, nothing is applicable everywhere.
>Plus it's
dangerous--you mess up the library you have to reinstall Visual Studio
and that takes several hours.
Nothing you do in the code editor can mess this up unless you mean
attempting to edit Visual Studio's resource files which is not at all
something somebody should be doing. Creating events is a simple thing you do
in code.

So, I would set up a user defined "Event" using a publisher-subscriber
model--I posted recently in this forum an excellent console mode
example of this--rather than using the Event handler stuff generated
by the code wizard.
If this was your "UnAwareClass" based example then I would be concerned
reading that by the comment chain posted in that thread, that you are still
trying to push it as an "excellent" example. No offence to yourself, as I
think your willingness to take part in the community is respectable, but if
clever people like MVP's have so much to say on your example, maybe it isnt
"excellent".

--
Ciaran O''Donnell
http://wannabedeveloper.spaces.live.com
"raylopez99" wrote:
On Jul 16, 10:47 pm, Swappy <Swa...@discussions.microsoft.comwrote:

Hey Swappy, I see three MVP's (Peter is also an MVP but he doesn't
like to talk about it) have answered your question, so far be it for
me to add my 0.02 dollars, but I would say that you should think twice
about passing parameters through Events other than as provided by
MSFT's wizards. Rule of thumb: don't mess with wizard generated
code, ever.

So I guess (if I read correctly) that I'm with Ciaran when he said:
"there is a bit of debate about it though as some people suggest that
it is not ideal to parse a reference to the sender and an EventArgs
derived class
to a set of event handlers that only need to know a boolean or and
int. They believe that having lots of derivations of EventArgs
introduces unnecessary code bloat and is a waste of time". Plus it's
dangerous--you mess up the library you have to reinstall Visual Studio
and that takes several hours.

So, I would set up a user defined "Event" using a publisher-subscriber
model--I posted recently in this forum an excellent console mode
example of this--rather than using the Event handler stuff generated
by the code wizard.

RL

( a newbie with a good month's worth--but a solid month--of C#
experience)
Jul 17 '08 #7
On Jul 17, 6:34*am, Ciaran O''Donnell
<CiaranODonn...@discussions.microsoft.comwrote:
Comments:
Hey Swappy, I see three MVP's (Peter is also an MVP but he doesn't
like to talk about it) have answered your question, so far be it for
me to add my 0.02 dollars,

errrrm.
I am NOT an MVP, and according to the Microsoft MVP awardies page, Peter
Duniho is not a current MVP holder
(https://mvp.support.microsoft.com/co...=peter+duniho).
I KNEW IT--PETER DUNIHO IS A FRAUD! HAHAHAHAHA THANKS CIARAN! HAHAHA
A FRAUD. But he's more knowledgeable than most about C# so let's not
rub it in. Love it. A fake. Like that guy on Wikipedia that claimed
to be a college professor on some subject and was unemployed trailer
park trash.
but I would say that you should think twice
about passing parameters through Events other than as provided by
MSFT's wizards. *Rule of thumb: *don't mess with wizard generated
code, ever.

Events in .NET are not normally generated by wizards. They are made with
code like:
public delegate void MyEventHandler(object sender, MyEventEventArgs e);
public event MyEventHandler MyEvent;
There is nothing autogenerated about the above code. It is just C# written
by hand in this windows to create an delegate type, and an event.
Sorry, I was not clear. I am saying the same thing, but saying that
when you click on an event handler like "_OnClick" using the Wizards,
the Events skeleton code is automatically generated by the Wizards,
that's all. I completely agree with you.

Wizards are great BTW-I'm using one now to create a MDI parent window
and child windows under Forms--great stuff.
>
This was a point of view that I raised as Devils Advocate rather than
voicing me own opinion. I tend to think of the phrase "Horses for courses",
as in, nothing is applicable everywhere.
So that's what that phrase means. Always wondered about that.
>
Plus it's
dangerous--you mess up the library you have to reinstall Visual Studio
and that takes several hours.

Nothing you do in the code editor can mess this up unless you mean
attempting to edit Visual Studio's resource files which is not at all
something somebody should be doing. Creating events is a simple thing youdo
in code.
Right. I meant if you mess with the resource files and/or .h headers
in C++ that are in the library--don't go there.
>
So, I would set up a user defined "Event" using a publisher-subscriber
model--I posted recently in this forum an excellent console mode
example of this--rather than using the Event handler stuff generated
by the code wizard.

If this was your "UnAwareClass" based example then I would be concerned
reading that by the comment chain posted in that thread, that you are still
trying to push it as an "excellent" example. No offence to yourself, as I
think your willingness to take part in the community is respectable, but if
clever people like MVP's have so much to say on your example, maybe it isnt
"excellent".
But some of them are imposter MVP's. That don't count. Is Jon Skeet
an MVP? Lemme check...he's been posting forever, I see his name from
eight years ago on the net...well I'll be damned, not only is he an
MVP, he's almost famous: "Jon is primarily a C# and Java developer in
Reading, England. In 2008 Manning published his book, "C# in Depth."
He has three young sons, and is currently working at Google".
Google, man I remember when they went public, and how the smart money
in Silcon Valley where I was at the time piled into those restricted
shares--they knew a good thing and made off like bandits.

RL

[N00b C# MVP, with a solid 30 days coding experience]
Jul 17 '08 #8
raylopez99 <ra********@yahoo.comwrote:
errrrm.
I am NOT an MVP, and according to the Microsoft MVP awardies page, Peter
Duniho is not a current MVP holder
(https://mvp.support.microsoft.com/co...=peter+duniho).

I KNEW IT--PETER DUNIHO IS A FRAUD! HAHAHAHAHA THANKS CIARAN! HAHAHA
A FRAUD. But he's more knowledgeable than most about C# so let's not
rub it in. Love it. A fake. Like that guy on Wikipedia that claimed
to be a college professor on some subject and was unemployed trailer
park trash.
Nope, that's just not a reliable way of deciding if someone's an MVP or
not. It just means that if Peter is an MVP (which I happen to know he
is, or at the very least *was*) then he's made his profile non-public.

It's easy to demonstrate that that's the case. You've just posted about
my public profile - go and see if you can find it again. I've just made
it non-public, and I think you'll find that if you look now, you won't
see it. The awardee directory does state fairly plainly: "The Microsoft
MVP Awardee directory contains a listing of all the MVPs that want to
share their information publicly."

Let me know when you've confirmed that, and I'll make my profile public
again...

It's a shame there isn't a "verify that XYZ is an MVP without showing a
profile" option, but that's just the way it goes.

My complete *guess* is that Peter won't go to the trouble of making his
profile public just to make a point, but I sincerely hope that if he
does so, you are ready to apologise for the insults quoted above.

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon_skeet
C# in Depth: http://csharpindepth.com
Jul 17 '08 #9
On Thu, 17 Jul 2008 06:34:01 -0700, Ciaran O''Donnell
<Ci************@discussions.microsoft.comwrote:
errrrm.
I am NOT an MVP, and according to the Microsoft MVP awardies page, Peter
Duniho is not a current MVP holder
(https://mvp.support.microsoft.com/co...=peter+duniho).
Just FYI: that directory includes only those MVPs who have specifically
enabled their profiles as being publicly visible, which I haven't (there's
not actually any useful information in my profile, and it's not like I
feel a need to _prove_ to anyone I'm an MVP, so I never bothered to enable
it).

You seem to have covered everything else. :)

Pete
Jul 17 '08 #10
On Thu, 17 Jul 2008 01:38:01 -0700, Ciaran O''Donnell
<Ci************@discussions.microsoft.comwrote:
Hey,
Jon Skeet is right with his suggestion about deriving from event args and
making you own delegate for the event.
Just to clarify: that's the normal approach if your class declares the
event and you have control over it. Otherwise, while you certainly could
proxy the event and copy the base EventArgs sub-class instance to a new
more-derived sub-class instance, IMHO it'd be better to just add a
parameter and pass the original EventArgs sub-class instance untouched.

The ambiguity is the reason I asked the OP what information he's trying to
pass and where it would come from. Basically, we don't know enough about
the OP's actual problem. If he's handling the Control.Click event,
creating a new EventArgs sub-class probably isn't the right way to go.

Pete
Jul 17 '08 #11
Sorry about the mistake Peter. I'll add it to the list of many times I should
have read the small print to avoid an embarassing or costly mistake.

Sincerest Apologies

--
Ciaran O''Donnell
http://wannabedeveloper.spaces.live.com
"Peter Duniho" wrote:
On Thu, 17 Jul 2008 06:34:01 -0700, Ciaran O''Donnell
<Ci************@discussions.microsoft.comwrote:
errrrm.
I am NOT an MVP, and according to the Microsoft MVP awardies page, Peter
Duniho is not a current MVP holder
(https://mvp.support.microsoft.com/co...=peter+duniho).

Just FYI: that directory includes only those MVPs who have specifically
enabled their profiles as being publicly visible, which I haven't (there's
not actually any useful information in my profile, and it's not like I
feel a need to _prove_ to anyone I'm an MVP, so I never bothered to enable
it).

You seem to have covered everything else. :)

Pete
Jul 18 '08 #12
On Jul 17, 1:58*pm, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
My complete *guess* is that Peter won't go to the trouble of making his
profile public just to make a point, but I sincerely hope that if he
does so, you are ready to apologise for the insults quoted above.
I confirmed your public profile was set to private, so you can turn it
back on now.

Peter doesn't want my apology--he's a tough old coot and enjoys the
'intellectual repartee' of sparring with somebody who is at least his
equal in smarts, and in coding maybe will be some day!

RL
Jul 18 '08 #13
On Jul 18, 10:39*am, raylopez99 <raylope...@yahoo.comwrote:
My complete *guess* is that Peter won't go to the trouble of making his
profile public just to make a point, but I sincerely hope that if he
does so, you are ready to apologise for the insults quoted above.

I confirmed your public profile was set to private, so you can turn it
back on now.
Thank you.
Peter doesn't want my apology--he's a tough old coot and enjoys the
'intellectual repartee' of sparring with somebody who is at least his
equal in smarts, and in coding maybe will be some day!
Leaving your assertion of being "at least [Peter's] equal in smarts"
to one side, are you seriously happy to call someone a fraud and not
apologise for it when you know you're wrong? Part of having a
civilised debate is respecting those you're debating with - and part
of showing respect is apologising when you're wrong. That's true even
for technical inaccuracies, but I'd say it's doubly important when
you've made inaccurate personal assertions.

Jon
Jul 18 '08 #14
On Fri, 18 Jul 2008 02:39:52 -0700, raylopez99 <ra********@yahoo.com>
wrote:
On Jul 17, 1:58Â*pm, Jon Skeet [C# MVP] <sk...@pobox.comwrote:
>My complete *guess* is that Peter won't go to the trouble of making his
profile public just to make a point, but I sincerely hope that if he
does so, you are ready to apologise for the insults quoted above.

I confirmed your public profile was set to private, so you can turn it
back on now.

Peter doesn't want my apology
Frankly Ray, it's not really a matter of what I want. It's true that I
have no real need of an apology from you, nor did I -- given your past
behavior -- actually expect one. But it's telling that given the
opportunity to offer one, you make a choice based on what you assert I
need or want, rather than what's the "right thing to do".

Given your participation in this newsgroup, my responses have been
targeted at just two goals: correcting misinformation, and trying to help
you improve your own communication skills (especially as they relate to
you apparently viewing yourself as a teacher). On the other hand, you
seem to revel in your own goal of prodding me with personal attacks.

I'm happy to ignore those attacks; after all, they say a lot more about
you than they do about me. But a person deserving of community respect
knows when they've crossed the line and _sincerely_ apologizes for it.

Now, I have my own personal thoughts on whether that really describes you
or not, but the fact is, if you're looking for credibility here, keeping
the bluster up even when you've made wildly false, personal accusations of
an individual is counter-productive to say the least. You really ought to
avoid the bluster altogether, but if you must engage in it, you ought to
at least equip yourself with the useful practice of apologizing when it's
gone wrong.

And again...I say this not for my own benefit, but for yours. I realize
it's difficult for you to see, but the two goals I described above really
do cover the extent of my intent. You have a determined interest in C#
programming and apparently the time and motivation to explore the language
and the framework. _If_ you could just take to heart some of the
criticisms and harness your powers for good, I think you could make some
real contributions here.

Pete
Jul 18 '08 #15
On Fri, 18 Jul 2008 02:23:02 -0700, Ciaran O''Donnell
<Ci************@discussions.microsoft.comwrote:
Sorry about the mistake Peter. I'll add it to the list of many times I
should
have read the small print to avoid an embarassing or costly mistake.
No problem at all. It was an honest mistake, and so I wouldn't call it
embarassing, nor did it seem costly (well, not to me or you, anyway :) ).
Jul 18 '08 #16
On Fri, 18 Jul 2008 09:41:17 -0700, raylopez99 <ra********@yahoo.com>
wrote:
On Jul 18, 9:27Â*am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
>I'm happy to ignore those attacks; after all, they say a lot more aboutÂ*
you than they do about me. Â*But a person deserving of community respect
knows when they've crossed the line and _sincerely_ apologizes for it.

OK, OKAY. Jeez I didn't realise you such a shrinking violet.
I'm not. You fail to get the point.
"I sincerely appologize" for flaming you. happy now?
I was happy before. Your quoted statement doesn't change that one way or
the other (nor does it seem sincere to me).

Until you fully comprehend what I actually wrote, I don't believe it will
be possible for you to offer a sincere apology. And it's clear you don't
comprehend what I wrote.

Pete
Jul 18 '08 #17
On Jul 18, 9:59*am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
>
Until you fully comprehend what I actually wrote, I don't believe it will*
be possible for you to offer a sincere apology. *And it's clear you don't *
comprehend what I wrote.
I'm REALLY sorry, OK? Besides I need guys like you to help me learn
C# and debug my code when I run into a brick wall, so I have to be
nice--self interest you know. So far though, I'm not having too many
problems with C# Forms, which seem to be more robust than the GUI
database stuff for C# (the frequent casting there seems terrible and
undocumented, and stuff is always not compiling even when copied from
a book).

RL
Jul 18 '08 #18
I am also having a similar problem.I would like to pass in an extra
parameter in my event handler being that I need the information
(curveArray = 2d array where each array has 64 values) to plot graphs on
the user interface. So heress the low down, I have a class called
CurveData that does calculations on data read from a unit via serial
port and returns a 2D array (curveArray) in the method called
initializeIgnComm. That information is passed into the event handler
getCurvesToolStripMenuItem_Click1, sorted to a list, and that list is
used in plotCurves to generate a plot. I don’t know if this is the best
way to go about this but I am unable to think of a way to get this
curveArray data without passing parameters in. So here is the event
handler code in my main form file as well as methods called in the event
handler:

//EVENT HANDLER
private void getCurvesToolStripMenuItem_Click1(object sender, int[,]
curveArray)
{
comm.DisplayWindow = rtbDisplay;
try
{
if (serialPort1.IsOpen)
{
comm.initializeIgnComm(serialPort1);
plotCurves(zedGraphControl1, curveArray);
}
else
{
MessageBox.Show("Error: COM port closed.");
return; // bail out
}
}
catch (System.Exception ex)
{
MessageBox.Show("Error - findIgnButton_Click Exception:
" + ex);
}

}
#endregion

private void plotCurves(ZedGraphControl zgc, int[,] curveArray)
{
GraphPane plotCurve = zgc.GraphPane; //Get a
reference to the GraphPane

// Set the Titles
plotCurve.Title.Text = "DFS726 IGNITION TIMING\n";
plotCurve.XAxis.Title.Text = "RPM(x100)";
plotCurve.YAxis.Title.Text = "Advance Angle(Degrees BTDC)";

PointPairList curve1 = new PointPairList(); //Create
curve1 list
sortData(curveArray); //Sort data into
list for plotting

LineItem ignCurve = plotCurve.AddCurve("WOT Curve 4",
curve1, Color.Red, SymbolType.Diamond);
zgc.AxisChange();

}
#endregion

private PointPairList sortData(int[,] curveArray)
{
int numberOfCurves = 8;
int[,] advDegBTDC = new int[numberOfCurves,8];
int[,] rpmValues = new int[numberOfCurves,8];
int curveNumber = 0;
int arrayIndex = 0;
int genArrayIndex = 0;

// Copy data from rpmArray and advArray into rpmValues and
advDegBTDC arrays used for plots
for (curveNumber = 0; curveNumber < numberOfCurves;
curveNumber++)
{
for (arrayIndex = 0; arrayIndex < 8; arrayIndex++)
{
advDegBTDC[curveNumber,arrayIndex] =
curveArray[0,genArrayIndex];
rpmValues[curveNumber,arrayIndex] =
curveArray[1,genArrayIndex];
genArrayIndex++;
}
}
PointPairList list1 = new PointPairList();

// TEST: Just sending the first curve (8 data points) to
list1 to graph
for (int i = 0; i < 8; i++)
{
list1.Add(rpmValues[0,i], advDegBTDC[0,i]);
}
return list1;

}
I’ve only been using C# for a couple weeks so forgive me if my coding is
not up to proper standards. Thanks in advance!


*** Sent via Developersdex http://www.developersdex.com ***
Oct 29 '08 #19
"dondigitech LaPel" <dl****@dynaonline.comwrote in message
news:uE**************@TK2MSFTNGP04.phx.gbl...
>I am also having a similar problem.I would like to pass in an extra
parameter in my event handler
I don't see the post that you replied to, so I'm making assumptions about
the original question.

My first assumption is that you're defining your OWN event handler and not
dealing with an event model that is out of your control. The .NET standard
is to pass only two parameters in an event handler: an instance of Object
that represents the object which raised the event (the sender) and an
instance of EventArgs--or a class derived from EventArgs--which contains all
the necessary information that a subscriber (consumer) might need. The part
about derived classes is important. If you need to provide information to
your event consumers then you should derive a class from EventArgs and add
properties to that class to hold that necessary data. (Well, unless the
Framework already provides a derived class which gives you exactly what you
need.)

Most of the time these properties are for one-way information: from the
sender to the consumer, but sometimes the consumer will pass information
back to the sender (an event which can be canceled is a perfect example of
this).
Oct 29 '08 #20
I still can't seem to get this to work. I created the event but was unable to
get anything to happen when I clicked on the button. This was the code in the
designer form file:

this.click += new
getCurveButtonHandler(this.getCurvesToolStripMenuI tem_Click);

So I've done the following in my main form file:

// Create EventArgs subclass to pass in 2D array parameter
public class EventArgs_2Darray : EventArgs
{
public int[,] curveArray;
public EventArgs_2Darray(int[,] array)
{
curveArray = array;
}
}
// Delegate declaration
public delegate void getCurveButtonHandler(object sender, int[,]
array);
public event getCurveButtonHandler click;

My event handler is:

private void getCurvesToolStripMenuItem_Click(object sender,
EventArgs_2Darray )
{
comm.DisplayWindow = rtbDisplay;
try
{
if (serialPort1.IsOpen)
{
comm.initializeIgnComm(serialPort1);
plotCurves(zedGraphControl1, curveArray);
}
else
{
MessageBox.Show("Error: COM port closed.");
return; // bail out
}
}
catch (System.Exception ex)
{
MessageBox.Show("Error - findIgnButton_Click Exception: " +
ex);
}

}

I still am not seeing how I can pass int[,] curveArray in as a parameter
because obviously I'm getting "The name 'curveArray' does not exist in the
current context" error. And in my designer form the click event is created as
such:

this.getCurvesToolStripMenuItem.Click += new
getCurveButtonHandler(this.getCurvesToolStripMenuI tem_Click);

The event Click built into the ToolStripMenuItem is handled by the
EventHandler which only passes in the 2 parameters (object sender, EventArgs
e). So, of course I get the "Error1 No overload for
'getCurvesToolStripMenuItem_Click' matches delegate
'PCComm.frmMain.getCurveButtonHandler' error. Since the ToolStripMenuItem
class is being used to initialize all the items on the menu strip i've used
(I have 3 which include the getCurvesToolStripMenuItem) is there a way to
just make this single item work passing in the 2D array parameter. I've tried
copying the entire ToolStripMenuItem class and adding another event that uses
my event handler getCurveButtonHandler but seems like this is not the best
solution. Need help!

"Jeff Johnson" wrote:
"dondigitech LaPel" <dl****@dynaonline.comwrote in message
news:uE**************@TK2MSFTNGP04.phx.gbl...
I am also having a similar problem.I would like to pass in an extra
parameter in my event handler

I don't see the post that you replied to, so I'm making assumptions about
the original question.

My first assumption is that you're defining your OWN event handler and not
dealing with an event model that is out of your control. The .NET standard
is to pass only two parameters in an event handler: an instance of Object
that represents the object which raised the event (the sender) and an
instance of EventArgs--or a class derived from EventArgs--which contains all
the necessary information that a subscriber (consumer) might need. The part
about derived classes is important. If you need to provide information to
your event consumers then you should derive a class from EventArgs and add
properties to that class to hold that necessary data. (Well, unless the
Framework already provides a derived class which gives you exactly what you
need.)

Most of the time these properties are for one-way information: from the
sender to the consumer, but sometimes the consumer will pass information
back to the sender (an event which can be canceled is a perfect example of
this).
Oct 30 '08 #21
On Thu, 30 Oct 2008 14:02:01 -0700, dondigitech
<do*********@discussions.microsoft.comwrote:
// Create EventArgs subclass to pass in 2D array parameter
public class EventArgs_2Darray : EventArgs
{
[...]
}
// Delegate declaration
public delegate void getCurveButtonHandler(object sender, int[,]
array);
public event getCurveButtonHandler click;

My event handler is:

private void getCurvesToolStripMenuItem_Click(object sender,
EventArgs_2Darray )
It would really help if you'd post the _actual_ code, copied and pasted.
Since your method declaration is missing the actual argument name for the
second argument, the above obviously isn't from a real program, which
makes it hard to provide a real answer.

That said...

Your delegate type needs to match the event handler itself. Your event
handler method takes as the second argument an instance of
EventArgs_2Darray, but your delegate type takes as the second argument a
two-dimensional "int[,]" array.

The most obvious fix is to change the argument type in the delegate type
from "int[,]" to "EventArgs_2Darray".

Note that an alternative to declaring the delegate type would be to just
use the generic EventHandler<Ttype:

public event EventHandler<EventArgs_2Darrayclick;

Now, there are other issues with the code that you've posted, not the
least of which is that the "Click" event is already a well-defined .NET
Control-class event that uses the EventHandler delegate type, and
redefining that for your own purpose is probably a big mistake. Other
issues are less significant, such as the use of a public field instead of
a property in the EventArgs sub-class, while other issues may be even more
significant, such as the question of what it is exactly you really want
this event handler to do and how you expect it to do it (so far, you've
been relatively vague on those specifics, making it difficult to provide a
good answer).

But at the very least, hopefully the above should help you move closer to
code that compiles. Once we get there, it'll probably be easier to answer
the really interesting parts of the question. :)

Pete
Oct 30 '08 #22
I did have both the delegate and event handler passing in the same params but
I changed it to see what would happen. Basically I have a class called
CurveData which reads data and calculates values and returns a 2D array which
I am trying to pass into the sortData and plotCurves methods in the main
form. A list is supposed to be generated which is then used in the plotCurves
method to display a graph. This is frustrating becuase it seems like i'm
close to getting this done but am having problems attacking this situation of
getting information from curveArray into this main form file. I hope this
clarifies my objective and the problems that I'm having. If you have any
advice for a different approach, it'd be much appreciated. Anywho, here is
the code from my main form file:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
using System.Threading;
using PCComm;
using PortSet;
using ZedGraph;

namespace PCComm
{
public partial class frmMain : Form
{
CurveData comm = new CurveData();
string transType = string.Empty;

// Create EventArgs subclass to pass in 2D array parameter
public class EventArgs_2Darray : EventArgs
{
public int[,] target;
public EventArgs_2Darray(int[,] array)
{
target = array;
}
}
// Delegate declaration
public delegate void getCurveButtonHandler(object sender,
EventArgs_2Darray e);
public event getCurveButtonHandler click;
public getCurveButtonHandler clickSubscribers
{
get { return click; }
}

public frmMain()
{
InitializeComponent();
}

private void frmMain_Load(object sender, EventArgs e)
{
//LoadValues();
//SetDefaults();
}

private void LoadValues()
{
}
//================================================== =====================================
# region MENU STRIP CONTROL
/// <summary>
/// Menu strip which controls serial port settings, opening and
closing the serial
/// port, acquiring ignition timing data as well as plotting out the
advance curves.
/// These functions below are executed in the event the user clicks
on a button on the
/// menu strip at the top of the form.
/// </summary>
//
//--------------------------------------------------------------------
//<<<<<<<<< SERIAL PORT SETTINGS MENU >>>>>>>>>>//
//--------------------------------------------------------------------
// Com port & baud rate settings can be changed by opening this menu.
//--------------------------------------------------------------------
private void settingsToolStripMenuItem_Click1(object sender,
EventArgs e)
{
// Make sure the port isn't already open
if (serialPort1.IsOpen)
{
MessageBox.Show("The port must be closed before changing the
settings.");
return;
}
else
{
// Create an instance of the settings form
PortSettings settings = new PortSettings();
if (settings.ShowDialog() == DialogResult.OK)
{
if (settings.selectedPort != "")
{
// Set the serial port to the new settings
serialPort1.PortName = settings.selectedPort;
serialPort1.BaudRate = settings.selectedBaudrate;
showSettings();
}
else
{
MessageBox.Show("Error: Settings form returned with
no COM port selected.");
return; // bail out
}
}
else
{
MessageBox.Show("Error: buttonSetup_Click - Settings
dialog box did not return Okay.");
return; // bail out
}
// Open the port
try
{
serialPort1.Close();
serialPort1.Open();
menuStrip1.Items[1].Text = "Close Port";
showSettings();
}
catch (System.Exception ex)
{
MessageBox.Show("Error - setupToolStripMenuItem_Click
Exception: " + ex);
}
}
}

//--------------------------------------------------------------------
//<<<<<<<<< OPEN/CLOSE PORT BUTTON >>>>>>>>>>//
//--------------------------------------------------------------------
// You can open or close the communication port by clicking this
button.
// Default settings are acquired if you have not changed them before
// clicking this button.
//--------------------------------------------------------------------
private void openPortToolStripMenuItem_Click(object sender,
EventArgs e)
{
try
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
menuStrip1.Items[1].Text = "Open Port";
}
else
{
serialPort1.Open();
menuStrip1.Items[1].Text = "Close Port";
}

showSettings();
}
catch (System.Exception ex)
{
MessageBox.Show("Error - openPortToolStripMenuItem_Click
Exception: " + ex);
}
}

private void GroupBox1_Enter(object sender, EventArgs e)
{

}

//--------------------------------------------------------------------
//<<<<<<<<< GET CURVES BUTTON >>>>>>>>>>//
//--------------------------------------------------------------------
// Once communication is established with the ignition unit. You
// are able to download ignition data by clicking on "Get Curves"
button.
// The ignition data downloaded from EEPROM is sorted and
// the advances are calculated and then plotted on the graph provided.
//--------------------------------------------------------------------
private void getCurvesToolStripMenuItem_Click(object sender,
EventArgs_2Darray e)
{
comm.DisplayWindow = rtbDisplay;
try
{
if (serialPort1.IsOpen)
{
comm.initializeIgnComm(serialPort1);
plotCurves(zedGraphControl1);
}
else
{
MessageBox.Show("Error: COM port closed.");
return; // bail out
}
}
catch (System.Exception ex)
{
MessageBox.Show("Error - findIgnButton_Click Exception: " +
ex);
}

}
#endregion
//================================================
# region CURVE ID HEADER
/// <summary>
/// The header on the Curve Identifier application displays serial
port status,
/// serial port name and baud rate.
/// </summary>
//================================================
private void showSettings()
{
this.Text = "DYNATEK IGNITIONS - " +
serialPort1.PortName + " " +
serialPort1.BaudRate.ToString();
if (serialPort1.IsOpen)
{
this.Text += " - Port is open";
}
else
{
this.Text += " - Port is closed";
}
}
#endregion
//================================================
# region GRAPH CURVES
/// <summary>
/// This function controls the graphing of the ignition advance
curves.
/// </summary>
//================================================
private void zedGraphControl1_Load(object sender, EventArgs e)
{
}

private void plotCurves(ZedGraphControl zgc)
{
GraphPane plotCurve = zgc.GraphPane; //Get a
reference to the GraphPane

int[,] curvePointsArray;
curvePointsArray = comm.GetData();

// Set the Titles
plotCurve.Title.Text = "DFS726 IGNITION TIMING\n";
plotCurve.XAxis.Title.Text = "RPM(x100)";
plotCurve.YAxis.Title.Text = "Advance Angle(Degrees BTDC)";

PointPairList curve1 = new PointPairList(); //Create curve1
list
sortData(curvePointsArray); //Sort data into
list for plotting

LineItem ignCurve = plotCurve.AddCurve("WOT Curve 4", curve1,
Color.Red, SymbolType.Diamond);
zgc.AxisChange();

}
#endregion

//--------------------------------------------------
// SORT ARRAY DATA TO POINTS FUNCTION
//--------------------------------------------------
private PointPairList sortData(int[,] curveArray)
{
int numberOfCurves = 8;
int[,] advDegBTDC = new int[numberOfCurves,8];
int[,] rpmValues = new int[numberOfCurves,8];
int curveNumber = 0;
int arrayIndex = 0;
int genArrayIndex = 0;

// Create array of arrays to store rpm and advance degree values
for ignition curves
//for (int q = 0; q < numberOfCurves; q++)
//{
// advDegBTDC[q,] = new int[8];
// rpmValues[q,] = new int[8];
//}

// Copy data from rpmArray and advArray into rpmValues and
advDegBTDC arrays used for plots
for (curveNumber = 0; curveNumber < numberOfCurves; curveNumber++)
{
for (arrayIndex = 0; arrayIndex < 8; arrayIndex++)
{
advDegBTDC[curveNumber,arrayIndex] =
curveArray[0,genArrayIndex];
rpmValues[curveNumber,arrayIndex] =
curveArray[1,genArrayIndex];
genArrayIndex++;
}
}
PointPairList list1 = new PointPairList();

// TEST: Just sending the first curve (8 data points) to list1
to graph
for (int i = 0; i < 8; i++)
{
list1.Add(rpmValues[0,i], advDegBTDC[0,i]);
}
return list1;

}
}
}

And here is the section code from the form designer file that applies to
this instance:

//
// getCurvesToolStripMenuItem
//
this.getCurvesToolStripMenuItem.Name =
"getCurvesToolStripMenuItem";
this.getCurvesToolStripMenuItem.Size = new
System.Drawing.Size(73, 20);
this.getCurvesToolStripMenuItem.Text = "Get Curves";
this.getCurvesToolStripMenuItem.Click += new
System.EventHandler(this.getCurvesToolStripMenuIte m_Click);

"Peter Duniho" wrote:
On Thu, 30 Oct 2008 14:02:01 -0700, dondigitech
<do*********@discussions.microsoft.comwrote:
// Create EventArgs subclass to pass in 2D array parameter
public class EventArgs_2Darray : EventArgs
{
[...]
}
// Delegate declaration
public delegate void getCurveButtonHandler(object sender, int[,]
array);
public event getCurveButtonHandler click;

My event handler is:

private void getCurvesToolStripMenuItem_Click(object sender,
EventArgs_2Darray )

It would really help if you'd post the _actual_ code, copied and pasted.
Since your method declaration is missing the actual argument name for the
second argument, the above obviously isn't from a real program, which
makes it hard to provide a real answer.

That said...

Your delegate type needs to match the event handler itself. Your event
handler method takes as the second argument an instance of
EventArgs_2Darray, but your delegate type takes as the second argument a
two-dimensional "int[,]" array.

The most obvious fix is to change the argument type in the delegate type
from "int[,]" to "EventArgs_2Darray".

Note that an alternative to declaring the delegate type would be to just
use the generic EventHandler<Ttype:

public event EventHandler<EventArgs_2Darrayclick;

Now, there are other issues with the code that you've posted, not the
least of which is that the "Click" event is already a well-defined .NET
Control-class event that uses the EventHandler delegate type, and
redefining that for your own purpose is probably a big mistake. Other
issues are less significant, such as the use of a public field instead of
a property in the EventArgs sub-class, while other issues may be even more
significant, such as the question of what it is exactly you really want
this event handler to do and how you expect it to do it (so far, you've
been relatively vague on those specifics, making it difficult to provide a
good answer).

But at the very least, hopefully the above should help you move closer to
code that compiles. Once we get there, it'll probably be easier to answer
the really interesting parts of the question. :)

Pete
Oct 30 '08 #23
On Fri, 31 Oct 2008 09:42:01 -0700, dondigitech
<do*********@discussions.microsoft.comwrote:
Formatting got all messed up again! I wasted my time copying into
notepad and
spacing it out!!
I really don't know what you mean. Here, the code looks reasonably fine.
Maybe the Microsoft Communities web site just isn't showing it correctly.

The problem isn't in the formatting, it's in the content.

See:
http://www.yoda.arachsys.com/csharp/complete.html
http://www.yoda.arachsys.com/csharp/incomplete.html
Oct 31 '08 #24
"dondigitech" <do*********@discussions.microsoft.comwrote in message
news:09**********************************@microsof t.com...
Ultimately the issue I am having is getting/passing the curveArray data to
the event handler.
Okay, this is where you lose me. I haven't looked too deeply into the code
because, quite frankly, there's way too much of it and I'm just not going to
take the time. I'm assuming that you've got a form, because you talked about
clicking a button. Now you want to pass something to the event handler.
Guess what: YOU CAN'T. The event handler is being called by the button, and
you don't have access to the button's internal code to control the way it
raises events and the data it passes. (I'm not even going to go into the
subject of inheriting from the button....)

So instead of going down the path of trying to get the desired data PASSED
IN to the event handler, you should instead be looking for a way to RETRIEVE
it once you're in the handler. It's your code; why wouldn't you have access
to the array you're looking for?
Oct 31 '08 #25

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Pavils Jurjans | last post by:
Hallo, I have been programming for restricted environments where Internet Explorer is a standard, so I haven't stumbled upon this problem until now, when I need to write a DOM-compatible code. ...
2
by: Adi | last post by:
Okay, this issue has been annoying me for a little while now. I need it to work on Mozilla 1.6 & IE 6 This is what I would like to be able to do: var row = document.createElement("TR"); var...
7
by: mg | last post by:
How can I call an event handler (e.g., Button1_Click) programmatically. That is, without having to click on the button with the mouse.
2
by: Jose Suero | last post by:
Hi all I have a dynamically created button, I can add an event handler with: AddHandler button.click, AddressOf static_function This works great, but what I need is to create a function that...
15
by: Amit D.Shinde | last post by:
I am adding a new picturebox control at runtime on the form How can i create click event handler for this control Amit Shinde
5
by: james | last post by:
Hello, I am having a little trouble creating an event handler for a context menu toolstripmenuitem. I've seen various tutorials and so on, but I keep getting a bit stuck! So far I have a second...
2
by: fusillo | last post by:
My code pass a value of a variable to the event handler's argument by means of eval statement here's: //statements setting evt for (var i=0; i<evt.periodi.length; i++){ //evt.periodi is an...
5
by: Tenacious | last post by:
I am trying to shutdown a database server in the Application_End event handler on the Global.asax page. So far I am trying this only on the development server that comes with Visual Studio 2005....
7
by: Andrus | last post by:
I noticed that DataGridView CellValidated() and other event handler first parameter is object: Grid.CellValidated+=new DataGridViewCellEventHandler(Grid_CellValidated); .... void...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.