¿Cómo descubrir el nombre del objeto de la persona que llama durante una función?
Pregunta
Estoy tratando de crear una "lista" usando LinkLabels para identificar archivos adjuntos (en un cliente de correo).Entonces, tengo esto para crear los enlaces:
Label newLabel = new LinkLabel();
newLabel.Name = "anexo" + Convert.ToString(anexos_file.Count); //anexos_file is a list where all the attachments Paths exist
newLabel.Text = Path.GetFileName(file);
newLabel.Left = bt_anexos.Left;
newLabel.Top = label2.Top;
newLabel.Width = 150;
newLabel.AutoSize = true;
newLabel.Click += new System.EventHandler(Click_anexo); //Click_anexo is the name of the function
Ahora necesito saber cómo hago una función que, cuando hago clic en el enlace, elimina el enlace en sí.
Entonces, ¿alguna ayuda?
Solución
private void Click_anexo(object sender, EventArgs arg)
{
}
Object sender
parameter contains information about the control which fired this event. Cast sender
as Label
LinkLabel lbl = (LinkLabel)sender;
and use it
lbl.Visible = false;
I think making it invisible is as good as deleted.
Otros consejos
in the Click_anexo
delegate you have to have sender
parameter.
That parameter is of object
type, but it is actually the control that raised that event.
Just cast it to the type you need and you done.
To respond to your statement and to clarify some of my comments.
To delete I just add: this.Controls.RemoveByKey(lbl.Name);
All you are doing here is removing your created control from its ControlCollection. The Control is still present and if you are creating a lot of these they will still be hanging around in memory. If you plan to reuse these controls then this fine, but if they are just for a onetime use you will be causing a memory leak. The way I would do it would be remove the eventhandler and dispose of the object like this:
private void Click_anexo(object sender, EventArgs e)
{
LinkLabel lbl = (LinkLabel)sender;
lbl.Click -= new EventHandler(Click_anexo);
lbl.Dispose();
}