Determining object sender name in click event

I

Ian Ornstein

I am coding a windows form. The form has several labels and I hoped to use
one click event because the processing to be done is very similar.

I just tried this:
void lblDayNoClick(object sender, System.EventArgs e)
{
MessageBox.Show(sender.ToString() );
}
and the result displayed in the MsgBox was
System.Windows.Form.Label, Text:13

How can I take the sender and determine the name of the object that
was clicked to cause this event?
I expect that since the actual object is sent, its properties should
be available.

If not, please suggest alternate approaches.

Thanks in advance,
- IanO -
 
P

Peter Rilling

You should be able to cast the sender to the Control class and access
properties for the object such as Name.
 
I

Ian Ornstein

Okay, I was able to get the Name of the control that invoked the Click event by:
void lblDayNoClick(object sender, System.EventArgs e)
{
System.Windows.Forms.Control lblTmp;
// lblTmp = (Control)sender; // This works
lblTmp = (System.Windows.Forms.Label) sender; // This also works
MessageBox.Show(lblTmp.Name);

However, if I want to do something with the control other than show its
Name, I need some other construct. The following code shows that I can
access the collection.

foreach (Label lbl in panel2.Controls)
{
MessageBox.Show(lbl.Name);
}

But this code still doesn't compile.
Can someone Please give me some correct syntax that will allow me to
change the properties of the clicked label?
panel2.Controls(lblTmp).BorderStyle = None;
}
- IanO -
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top