Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

function paremeters 1

Status
Not open for further replies.

jslmvl

Vendor
Jan 26, 2008
268
GB
Hi,

I found that in
public void button_Click(Object s, EventArgs e)
{
}
we must have the paramenters Object s and EventArgs e, but we can simply do
void Page_Load()
without any paremeter.

Am I right? Why?
 
Yes, you're right. The button's click is a delegate and that's why it has parameters passed to it.
 
Thanks.

Can you tell me what is a delegate? Page_Load() is not a delegate?
 
a delegate is the contract between the event and the handler what is important is the type signatures. this is the default format
Code:
public void button_Click(Object sender, EventArgs e)
{
}
however you could also write it this way
Code:
public [COLOR=blue]void[/color] DoSomeWork([COLOR=blue]Object[/color] theControl, [COLOR=blue]EventArgs[/color] uselessForClickEvents)
{
}
the blue text is how the compiler knows the signature/contract is met.
a delegate acts as a pointer to code that can execute in the future. another way to define it: differed execution of code. a delegate doesn't have to be a method. you can also write it this way
Code:
MyButton.Click += delegate(object o, EventArgs e) 
{
   //put code here to do work.
};
with .net 3.5 lambda expressions can shorten this even more
Code:
MyButton.Click += (o, e) { do work here };
if your first introduction to delegates/events is webforms then it will be hard to grasp. webforms try to do almost everything for you through wizards and drag/drop so you don't have to understand the code.
for example. when you drag a button on to a webform and double click the control. the auto code you see is:
Code:
public void Button1_Click(object sender, EventArgs e)
{
}
what VS and webforms does for you is
Code:
if you open up the designer code you will also find code that looks like this (most likely in the init event)
[code]
protected override void Init(EventArgs e)
{
   Button Button1 = new Button();
   Button1.ID = "Button1";
   Button1.Click += new EventHandler(Button1_Click);

   Controls.Add(Button1);
}
maybe not that exact, but it's in the designer code file.

this scratches the surface of events/delegates in the context of webforms.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top