views:

303

answers:

1

Hello

I have an issue with dynamic, runtime controls.

I create a group of controls per record to display on a form.

I add the record ID as a tag on each of the controls to identify which record they belong to.

While rCONT.Read
    Dim txtphome As New TextBox
    txtphome.Name = "phone" + rCONT.Item("pcontID").ToString
    txtphome.Text = rCONT.Item("pcontPhHome").ToString
    txtphome.Tag = rCONT.Item("pcontID").ToString
    tcPatientDetails.TabPages(2).Controls.Add(txtphome)
       AddHandler txtphome.LostFocus, AddressOf SaveContactChange
       AddHandler txtphome.GotFocus, AddressOf SetContactNumber
End While

In SetContactNumber I want to save the tag value How can I identify which control triggered it

+4  A: 

Let's say your SetContactNumber event is defined as:

C#

  private void SetContactNumber(object sender, EventArgs e)
  {
      //Stuff that happens when the SetContactNumber event is raised...
  }

VB

  Private sub SetContactNumber(sender As object, e As EventArgs)
      //Stuff that happens when the SetContactNumber event is raised
  End Sub

The Sender parameter is the object that raised the event. So you just need to cast it and attach the value to the tag:

C#

  ((textbox)sender).tag = "Whatever you wanted to put in here";

VB

  CType(sender, textbox).tag = "Whatever you wanted to put in here"

The tag property takes a value of type object, so the value assigned could be anything you like: string, object, instance of a class etc. It's your responsibility to cast that object when you're pulling it out of the tag property to use it though.

So when you put it all together, this will pull the object that raised the event, cast it as a textbox and dump the value you specify into the tag property.

C#

  private void SetContactNumber(object sender, EventArgs e)
  {
      textbox thisTextbox = (textbox)sender;
      thisTextbox.tag = "Whatever you wanted to put in here";
  }

VB

  Private Sub SetContactNumber(sender As Object, e As EventArgs)
      Dim thisTextbox As TextBox = CType(sender, Textbox)
      thisTextbox.tag = "Whatever you wanted to put in here"
  End Sub
BenAlabaster
+1; good explanation. But I got the impression that he assigned the tag in the loop and wanted to use it in the event handler (but it was a tad unclear).
Fredrik Mörk
It *was* a tad unclear... and then right after that, I realised I wrote all my example in c# and he wanted VB...
BenAlabaster