c# - 如何为动态创建的标签添加点击事件

标签 c# winforms events dynamic

Label[] l1 = new Label[30];    
DataTable dt = ConsoleApp2.CitiesDB.getCities(this.region);
                foreach(DataRow row in dt.Rows)
                {
                    count++;
                    string city = row.Field<string>("city");
                    l1[count] = new Label();
                    l1[count].Location = new System.Drawing.Point(x,y);
                    l1[count].Size = new Size(140, 80);
                    l1[count].Font = new System.Drawing.Font("Century Gothic", 8.5F);
                    l1[count].Text = city;
                    x = x + 260;
                    this.Controls.Add(l1[count]);
                    this.Refresh();
                    if(count == 4 || count %4 ==0)
                    {
                        y = y + 150;
                        x = 40;
                    }
                //l1[count].Click += new EventHandler(l1_click);
            }

所以我制作了一个动态标签(每个标签是一个城市名称)。我怎样才能使每个标签可点击?我有一个注册表单 - 我想要的是,如果用户单击“纽约”,那么它将出现在“城市”文本框中。使用 EventHandler 的方式对我不起作用);。我能做些什么? 我在不起作用的代码中的意思是:

protected void l1_click(object sender, EventArgs e)
    {
        RegisterForm register = new RegisterForm(username,email,password,address,phone);
        register.state.Text = region;
        register.city.Text = l1[count].Text;
        register.Show();
    }

谢谢(:

最佳答案

为每个标签分配一次点击事件(动态创建):

l1[count].Click += l1_click;

在一键单击事件中,使用 sender 参数来查看单击了哪个标签:

protected void l1_click(object sender, EventArgs e)
{
  Label lbl = (Label)sender;
  MessageBox.Show(lbl.Text);
}

关于c# - 如何为动态创建的标签添加点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46820902/

相关文章:

c# - 如何从字符串中解析特定的函数名及其参数?

javascript 类实例处理事件不一致 - this/范围界定困惑

javascript - jQuery 防止更改选择

c# - 结构图配置异常

c# - System.InvalidOperationException : The type [XYZ] may not be used in this context. BUG确认

c# - 如何每天影响变量 C# asp.net

javascript - 延迟 25/30 毫秒的 CSS3 animationStarted 事件触发

c# - 以图形方式显示正在执行的代码? 。网

.NET 拆分器控件显示

c# - mdi 子窗体最大化窗口状态 - BorderStyle