0

I'm trying to create a "list" using linklabels to identify attachments (in a mail client). So, I've this to create the links:

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

Now I need to know how do I make a function that, when I click the link, deletes the link itself.

So, any help?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
João Borrego
  • 95
  • 2
  • 12

3 Answers3

2

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.

Tigran
  • 61,654
  • 8
  • 86
  • 123
1
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.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
0

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();
}
Mark Hall
  • 53,938
  • 9
  • 94
  • 111