【问题标题】:c# adding dynamic click eventc# 添加动态点击事件
【发布时间】:2017-10-18 23:49:54
【问题描述】:
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();
    }

谢谢(:

【问题讨论】:

    标签: c# winforms dynamic


    【解决方案1】:

    为每个标签分配一个点击事件:

    l1[count].Click += l1_click;
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 2019-04-06
      • 2019-11-30
      • 1970-01-01
      相关资源
      最近更新 更多