3

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>

StuartLC
  • 104,537
  • 17
  • 209
  • 285
Jack
  • 16,276
  • 55
  • 159
  • 284

1 Answers1

2

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);
}
StuartLC
  • 104,537
  • 17
  • 209
  • 285
  • 1
    The `if` check isn't even needed and `Clear()` is much better than `RemoveAt()` (in that contexto). Thanks! – Jack Dec 20 '14 at 07:24
  • FWIW: The LinkLabel implementation does prevent overlapping links, but the logic used might not be what you want or expect. – Tom Bogle Dec 22 '20 at 15:00