简体   繁体   中英

c# adding dynamic click event

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

So i made a dynamic labels (each label is a city name). how can i make each label clickable? i have a register form - what i want is if user clicks on "new york" then in the "city" textbox it will appear. the way with the EventHandler doesnt works for me);. what can i do? what i mean in code that doesnt work:

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

thanks (:

Assign one click event for each label:

l1[count].Click += l1_click;

In the click event use the sender argument to see which label was clicked on:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM