Is there any situation when I should prefer to use the sender
parameter of the controls' event handlers instead of the direct access to required control?
So instead of
private void okButton_Click(object sender, EventArgs e)
{
okButton.Enabled = false;
}
I should use
private void okButton_Click(object sender, EventArgs e)
{
(sender as Button).Enabled = false;
}
Is there any benefit at all?
As LarsTech indicated in comment, if you have multiple "Clicks" being handled by the same function, using sender can be advantageous to prevent duplicate code.
Terrible example, but if you have:
<asp:Button ID="Button1" runat="server" Text="Not Clicked" OnClick="Button_Click" />
<asp:Button ID="Button2" runat="server" Text="Not Clicked" OnClick="Button_Click" />
<asp:Button ID="Button3" runat="server" Text="Not Clicked" OnClick="Button_Click" />
Your handler:
protected void Button_Click(object sender, EventArgs e)
{
(sender as Button).Text = "Totes clicked";
}
vs having 3 handlers that do the same thing, but for each individual button.
Additionally, when working with controls
within repeaters
or within a datagrid
, you wouldn't necessarily be able to access your control
by its name directly, in instances like this sender
can be a more attractive option over trying to cast it by row index.
The main use is when you use one handler method to handle event of multiple objects. This way you can concentrate your code in one central method.
Another usage is when you creates controls at runtime and assign event handler to them. In such cases you must use this method.
Somewhere attach a handler to event of your controls.
this.NewToolStripButton.Click += new System.EventHandler(this.ToolStripButton_Click);
this.EditToolStripButton.Click += new System.EventHandler(this.ToolStripButton_Click);
this.DeleteToolStripButton.Click += new System.EventHandler(this.ToolStripButton_Click);
this.DetailsToolStripButton.Click += new System.EventHandler(this.ToolStripButton_Click);
Thene use it this way:
private void ToolStripButton_Click(object sender, EventArgs e)
{
var toolstripItem = sender as ToolStripItem;
if (toolstripItem == null)
return;
switch(toolstripItem.Name)
{
case "NewToolStripItem":
//Do New stuff here
break;
case "EditToolStripItem":
//Do Edit stuff here
break;
case "DeleteToolStripItem":
//Do Delete stuff here
break;
case "DetailsToolStripItem":
//Do Details stuff here
break;
default:
break;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.