Making dynamically created linklabels clickable in Winforms

ⅰ亾dé卋堺 提交于 2019-12-10 20:31:32

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/19934186/making-dynamically-created-linklabels-clickable-in-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!