简体   繁体   中英

run-time controls eventhandler windows forms

I am drawing a row of labels at run-time and attaching the name property to identify them How do i get the eventhandler to get the selected/clicked run-time control property(text)

   for (int yy = 1; y < 40; y++)
   {
     Label TT = new Label();
     TT.Name = "TT" + yy.ToString();
     TT.Location = new Point(xx, zz);
     TT.BorderStyle = BorderStyle.FixedSingle;
     TT.Click+= new EventHandler(TT_Click);
     TT.Width = 20;
     TT.Text = yy.ToString();
      this.Controls.Add(TT);
       xx += 20;
    }

   void TT_Click(object sender,EventArgs e)
        {
               ???????????????
        }

sender should be the thing:

void TT_Click(object sender,EventArgs e) {
  var label = (Label)sender;
}

Then do as you will with it, identify it and so on.

Beware, though, of these handlers being called improperly: too many times I've seen programmers invoke these 'manually' in code such as TT_Click(null, new EventArgs()) etc. You'd do well to do some sanity checking as part of the logic.

 void TT_Click(object sender,EventArgs e) {
     if(sender == null) return; //return if the sender object is null
     MessageBox.Show(((Label)sender).Text); //Shows a MessageBox whith the Text of the Label
 }

Sender is an object which contains the sender of this event, in your case one of the labels. Now you have to cast it into a label and you can access the text-property.

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