How to Insert LinkLabel into DataGridViewCell C#

286 Views Asked by At

Trying to find a way to create a DataGridViewCell that supports multiple links, like this:

Multiple Links in a GridView Example

I know this has been asked a thousand times (I've spent a day combing through them), but please hear me out. I would like one cell to contain multiple links separated by commas. I have found a way to do this with a LinkLabel:

var addresses = new List<string>
{
    "http://www.example.com/page1",
    "http://www.example.com/page2",
    "http://www.example.com/page3",
};

var stringBuilder = new StringBuilder();
var links = new List<LinkLabel.Link>();

foreach (var address in addresses)
{
    if (stringBuilder.Length > 0) stringBuilder.Append(", ");

    // We cannot add the new LinkLabel.Link to the LinkLabel yet because
    // there is no text in the label yet, so the label will complain about
    // the link location being out of range. So we'll temporarily store
    // the links in a collection and add them later.
    links.Add(new LinkLabel.Link(stringBuilder.Length, address.Length, address));
    stringBuilder.Append(address);
}

// We must set the text before we add the links.
linkLabel1.Text = stringBuilder.ToString();
foreach (var link in links)
{
    linkLabel1.Links.Add(link);
}
linkLabel1.AutoSize = true;
linkLabel1.LinkClicked += (s, e) =>
{
    MessageBox.Show((string)e.Link.LinkData);
};

LinkList with Multiple Links Output

I cannot find a way to add this LinkList to a DataGridViewCell. Is it possible to somehow insert this LinkLabel into a DataGridViewCell and still have it function correctly? Or can this same functionality somehow be obtained by using a DataGridViewLinkColumn somehow?

0

There are 0 best solutions below