Re: Just what the h can we do with "sender" - new guy question



On 2 Nov, 05:09, "T.Davis" <trevorhughda...@xxxxxxxxx> wrote:
All apologies, but how do you cast event sender object in c#?

string s = (string)sender;

like so?

On Nov 2, 12:11 am, not_a_commie <notacom...@xxxxxxxxx> wrote:



I use it in cases where I have the possibility of receiving an event
that I send. I ignore events sent from myself. In that case all you
have to do is a pointer compare (== by default on classes) without
casting the object.- Hide quoted text -

- Show quoted text -

String is a bad example as strings don't raise events. Take a look at
the following example. It's very simple. One form, two buttons using
the same click handler to increment their label. Watch for line wrap.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

namespace WindowsApplication30
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;

private System.ComponentModel.Container components = null;

public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();

this.button1.Location = new System.Drawing.Point(16, 16);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(112, 40);
this.button1.TabIndex = 0;
this.button1.Text = "1";
this.button1.Click += new System.EventHandler(this.button_Click);
this.button2.Click += new System.EventHandler(this.button_Click);

this.button2.Location = new System.Drawing.Point(16, 64);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(112, 40);
this.button2.TabIndex = 1;
this.button2.Text = "1";

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion

[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void button_Click(object sender, System.EventArgs e)
{
if(sender is Button)
{
Button b = (Button)sender;
int c = int.Parse(b.Text);
c++;
b.Text = c.ToString();
}
}
}
}

.