c# object sender or something

Discussion in 'Software' started by mastermosley, Nov 8, 2010.

  1. mastermosley

    mastermosley Sergeant

    I have it set up so that all my textboxs use the same TextBoxChange Event.

    Textbox txt = ((Textbox)sender)

    but depending on the textbox they are changing it using information from the corsponding textbox. txt1 corsponds to lbl1, txt2 corsponds to lbl2 ect. Is there anyway I can trim the last digit of the sender (so if txt1 is the textbox i changed ) i can get the 1 and add it to say Label lbl = lbl(trimmeddigit).Text or something like that? I have a lot of textboxes and making an event for each one would be very un efficent code, any ideas??
     
  2. mastermosley

    mastermosley Sergeant

    I was able to get the number from the TextBox
    string last = txt.Name.Substring(txt.Name.Length - 1, 1);

    so now: string controlname = "lbl" + last; which would be lbl1 how to I reference that now to the actual lbl1 control?
     
  3. Wyatt_Earp

    Wyatt_Earp MajorGeek

    In order to get a control from a form by it's name, you would use:

    (from the form namespace)
    this.Controls.Find("lbl1", true);

    You can narrow the search down if the control is inside a group box or a tab page or something like that and change true to false so it doesn't have to search through all the child controls of the container.

    A better way to do this, if the labels are always tied to the same text box might be to use the .Tag property of the textboxes. When you instantiate the text boxes, set textbox.Tag equal to the label that you want to reference. Then instead of parsing the textbox name for the number and searching for that label, all you have to do is get the textbox and you have a reference to the label in the .Tag property.
     
  4. mastermosley

    mastermosley Sergeant

    Awesome, Thanks.
     

MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds