Pregunta

I am making a program that will allow a user to click on a business name created by dynamic link labels.

I have never used link labels in C# before an wanted to know how one does that. The number of businesses that can be generated for a partucular user varies so the link labels are not the same in number for every user.

I then want to capture the business ID to make a Json call.

My code to populate business names

// fill in the business names as linked labels
if (GlobalClass.Businesses != null)
{
     tableLayoutPanel.Controls.Clear();                     

     foreach (var business in GlobalClass.Businesses)
     {
          tableLayoutPanel.Controls.Add(new LinkLabel { Text = business.businessName.ToString() });
     }
}

The business class looks like this and business in business above is a list.

public class Business
{
    public string businessID { get; set; }
    public string businessName { get; set; }
}

What do I need to do in order to capture the business Id on the click of a business name?

I have looked at Dynamically creating Link Labels using foreach in c# but it did not help much

¿Fue útil?

Solución

Declare click handler:

private void MyLinkClick(object sender, ...)
{
    var linkLabel = (LinkLabel) sender;
    var business = (Business) linkLabel.Tag;
    /* do something with business */
}

Change your foreach:

foreach (var business in GlobalClass.Businesses)
{
     var linkLabel = new LinkLabel { Text = business.businessName.ToString(), Tag = business };
     linkLabel.Click += MyLinkClick;
     tableLayoutPanel.Controls.Add(linkLabel);
}

Otros consejos

Set the Tag property of the LinkLabel equal to that of your business.businessID property. Add a handler for the LinkLabel and when the item is clicked, cast the sender to a LinkLabel and access the Tag property.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top