Skip to content

Passing parameters to a eventhandler?

Ken

Asked Nov 30, 2010, 5:55 PM EST1 answer
Share
LinkedInX
Hi.  I have an image tagging feature on a media program I'm writing.  I want to have a grid of textboxes where the user can type in tags they tend to use a lot, then they can double click the textbox to insert the tag.  I did some reading on how to programmatically create controls and eventhandlers with parameters and I am at this point:

TypeScript
for (int cnt = 0; cnt<=4; cnt++) {
  TextBox txt = new TextBox();
  txt.Location = new System.Drawing.Point(303, 324 + (cnt * 26));
  txt.Name = "quickAdd" + cnt.ToString();
  txt.Size = new System.Drawing.Size(102, 20);
  txt.Visible = true;
  txt.DoubleClick += (snd, arg) => textbox_DoubleClick(cnt.ToString());
  tabPage7.Controls.Add(txt);
} 

private void textbox_DoubleClick(object id) {
  MessageBox.Show(id.ToString());
}

That creates the controls fine.  However, no matter which one I double click the messagebox says "5".  I changed out cnt.tostring and put "test" and got my "test" fine.  Why doesn't it work with the passing of the iterator?  Does it perhaps view the "cnt.ToString" as something to process at double click time literally; like pass the value of cnt variable instead of 1,2,3?  If so, how do I get around that?

I just need to be able to identify in the event fired function what textbox called the func so I know what text to paste.  Ugh!

Thanks.

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    Well, I figured it out.  I don't know how efficient this is, but it works:

    TypeScript
    for (int loop = 1; loop<=4; loop++) {
      for (int cnt = 1; cnt<=5; cnt++) {
        TextBox txt = new TextBox();
        switch (loop) {
        case 1:
          txt.Location = new System.Drawing.Point(303, 298 + (cnt * 26)); break;
        case 2:
          txt.Location = new System.Drawing.Point(411, 298 + (cnt * 26)); break;
        case 3:
          txt.Location = new System.Drawing.Point(520, 298 + (cnt * 26)); break;
        case 4:
          txt.Location = new System.Drawing.Point(628, 298 + (cnt * 26)); break;
        }
        txt.Name = "quickAdd" + (((loop-1)*5)+cnt).ToString();
        txt.Size = new System.Drawing.Size(102, 20);
        txt.Visible = true;
        txt.DoubleClick += (snd, arg) => textbox_DoubleClick(txt.Name);
        tabPage7.Controls.Add(txt); 
      }
    }
    
    private void textbox_DoubleClick(object id) {
      Control[] grr = this.Controls.Find(id.ToString(), true);
      if (!ExistingTags.Lines.Contains(grr[0].Text.ToLower())) ExistingTags.Text += grr[0].Text.ToLower() + Environment.NewLine;
    }
    0