Search code examples
c#linklabel

Dynamic Generated LinkLabels - passing unique information to the handler


What I am trying to do: Generate a list of clickable links that when you click them they display a more detailed window about them, next to them.

What I can't figure out is how to identify the LinkLabel after its clicked.

Here is my code so far:

if (reader.HasRows)
        {
            lore_output_panel.Controls.Clear();
            string lore_search_returns = "";
            int i = 0;
            LinkLabel[] itemfound = new LinkLabel[20];
            while (reader.Read() && i < 20)
            {
                itemfound[i] = new LinkLabel();
                itemfound[i].Text = reader["name"].ToString();
                Point p = new Point(0, 0 + (15 * i));
                itemfound[i].Location = p;
                itemfound[i].Visible = true;
                itemfound[i].AutoSize = true;
                itemfound[i].Show();
                itemfound[i].Name = "loreitem" + i;
                itemfound[i].LinkClicked += new LinkLabelLinkClickedEventHandler(this.linkClicked);
                lore_output_panel.Controls.Add(itemfound[i]);
                i++;
                //lore_search_returns += reader["name"] + "\r\n";
            }
            lore_output.Text = lore_search_returns;
        }
        else
        {
            lore_output.Text = "ITEM NOT FOUND\r\n" + sql;
        }
        m_dbConnection.Close();
    }
    private void linkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        string testname = this.Name;
        MessageBox.Show(testname);
    }

With this code, when the link is clicked, it just shows the Form's name. I need some kind of unique identifier to come through on the click so I can identify which linklabel was clicked. Is there a way to pass the name of the linklabel I clicked through the click event handler?

I have a feeling it may have to do with tags (as seen at this link) Making dynamically created linklabels clickable in Winforms but I don't understand.


Solution

  • You are confusing this the form with sender the actual linkLabel. You can cast the sender as a linkLabel and then access its names without resorting to the tag property, which can also hold additionnal data.

    e.g.

    private void linkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        string testname = ((LinkLabel)sender).Name;
        MessageBox.Show(testname)
    }