How to change text and link in Windows Forms LinkLabel

I would like to have only the link and all the text that can be clicked and dynamically set. I don't know how to replace them. I tried below code and when it gets called more than once I get an error null pointer exception

.

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);
}

      

which is called like this:

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

      

Foo

:

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

      

and fooArr

justList<Foo>

+3


source to share


1 answer


Since the collection LinkLabel.Links

references the start position and length of the hyperlinked string, I believe there is a problem if LinkLabel.Links

there is already more than one link in the collection that references an existing one Text

. When you replace the text and only the first link, it means that existing links are now referring to portions of the string that are longer than the new one and / or can 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 all text and all links every time, so this can be easily set 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);
}

      

+2


source







All Articles