Search code examples
c#winformslinklabel

How can I Change the Text and Link of a Windows Forms LinkLabel


I'd like to have only a link and the entire text clickable and both dynamically set. I don't know how to replace them. I tried below code and when it gets called more than one time I get null pointer exception error.

I tried using this:

void setLink(string label, string link)
{
    linkLabel1.Text = label;

    if (linkLabel1.Links.Count > 0)
    {
        linkLabel1.Links.RemoveAt(0);
    }

    linkLabel1.Links.Add(0, label.Length, link);
}

that's called from like this:

foreach(Foo f in fooArr) {
   setLink(f.name, f.url);
   // ... do something
} 

Foo is:

public class Foo
{
  public string name { get; set; }
  public string url { get; set;  }
}

and fooArr just List<Foo>


Solution

  • Because the LinkLabel.Links collection makes reference to a start position and length of the hyperlinked label string, I believe there is an issue if there is already more than one link in the LinkLabel.Links collection, which links to an existing Text. When you replace the text, and just the first link, it means that the existing links now reference parts of a string which are longer than the new string, and / or it may create overlapping links.

    linkLabel1.Text = "A really long link and I'm linking the last bit";
    linkLabel1.Links.Add(0, 5, "www.removeme.com");
    var longLength = linkLabel1.Text.Length;
    linkLabel1.Links.Add(longLength - 5, longLength - 1, "endofstring.com");
    setLink("short", "newlink.com"); // What about endofstring.com?
    

    If I understand you correctly, you want to replace the whole text and all links every time, so this is easily fixed with Links.Clear() to remove all links:

    void setLink(string label, string link)
    {
        linkLabel1.Text = label;
        linkLabel1.Links.Clear();
        linkLabel1.Links.Add(0, label.Length, link);
    }