Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Retrieve the control's name

Retrieve the control's name

Scheduled Pinned Locked Moved C#
tutorialquestion
10 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I Offline
    I Offline
    Islorvat
    wrote on last edited by
    #1

    Hello! I'm working on an application wich will alow the user to add and remove controls. I want to apply different rules to textbox and this rules will be different for every textbox. For example i want to check wich control has been clicked by using a click event. Because i don't know how many textboxes will the user create i've decided to go along with the code below:

        private void Form1\_Load(object sender, EventArgs e)
        {
            foreach (Control ctrl in Controls)
            {
                ctrl.Click += new EventHandler(ctrl\_Click);
            }
        }
    
        void ctrl\_Click(object sender, EventArgs e)
        {
    
        }
    

    Is there anyway that i can get the name of the control that has been clicked? The sender.Tostring() only returns the type and the text of the control. Thanks! ;)

    R C B 3 Replies Last reply
    0
    • I Islorvat

      Hello! I'm working on an application wich will alow the user to add and remove controls. I want to apply different rules to textbox and this rules will be different for every textbox. For example i want to check wich control has been clicked by using a click event. Because i don't know how many textboxes will the user create i've decided to go along with the code below:

          private void Form1\_Load(object sender, EventArgs e)
          {
              foreach (Control ctrl in Controls)
              {
                  ctrl.Click += new EventHandler(ctrl\_Click);
              }
          }
      
          void ctrl\_Click(object sender, EventArgs e)
          {
      
          }
      

      Is there anyway that i can get the name of the control that has been clicked? The sender.Tostring() only returns the type and the text of the control. Thanks! ;)

      R Offline
      R Offline
      Rob Philpott
      wrote on last edited by
      #2

      Yes, what you want to do is cast the sender to a Control such:

      void ctrl_Click(object sender, EventArgs e)
      {
      Control contol = sender as Control;

      if (control != null)
      {
          string name = control.Name;
      }
      

      }

      Regards, Rob Philpott.

      1 Reply Last reply
      0
      • I Islorvat

        Hello! I'm working on an application wich will alow the user to add and remove controls. I want to apply different rules to textbox and this rules will be different for every textbox. For example i want to check wich control has been clicked by using a click event. Because i don't know how many textboxes will the user create i've decided to go along with the code below:

            private void Form1\_Load(object sender, EventArgs e)
            {
                foreach (Control ctrl in Controls)
                {
                    ctrl.Click += new EventHandler(ctrl\_Click);
                }
            }
        
            void ctrl\_Click(object sender, EventArgs e)
            {
        
            }
        

        Is there anyway that i can get the name of the control that has been clicked? The sender.Tostring() only returns the type and the text of the control. Thanks! ;)

        C Offline
        C Offline
        c0ax_lx
        wrote on last edited by
        #3

        Hi. void ctrl_Click(object sender, EventArgs e) { if (sender.GetType() == typeof(TextBox)) { string name = ((TextBox)sender).Name; } } should work. Also if you are only interested in handling clicks for textboxes you could change the foreach loop to: foreach (Control ctrl in Controls) { if (ctrl.GetType() == typeof(TextBox)) { ctrl.Click += new EventHandler(ctrl_Click); } }

        If it' stuck, DO NOT pull harder!

        L 1 Reply Last reply
        0
        • C c0ax_lx

          Hi. void ctrl_Click(object sender, EventArgs e) { if (sender.GetType() == typeof(TextBox)) { string name = ((TextBox)sender).Name; } } should work. Also if you are only interested in handling clicks for textboxes you could change the foreach loop to: foreach (Control ctrl in Controls) { if (ctrl.GetType() == typeof(TextBox)) { ctrl.Click += new EventHandler(ctrl_Click); } }

          If it' stuck, DO NOT pull harder!

          L Offline
          L Offline
          Luc Pattyn
          wrote on last edited by
          #4

          do NOT compare strings to check for a type, instead use the appropriate keywords: do NOT compare types, nor strings representing types, instead use the appropriate keywords:

          if (sender is TextBox) log("this is a TextBox");
          // or
          TextBox tb=sender as TextBox;
          if (tb!=null) log("this is a TextBox");

          it is both faster and more correct as it also matches derived types. :)

          Luc Pattyn [Forum Guidelines] [My Articles]


          I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


          modified on Saturday, November 28, 2009 7:37 AM

          C 1 Reply Last reply
          0
          • L Luc Pattyn

            do NOT compare strings to check for a type, instead use the appropriate keywords: do NOT compare types, nor strings representing types, instead use the appropriate keywords:

            if (sender is TextBox) log("this is a TextBox");
            // or
            TextBox tb=sender as TextBox;
            if (tb!=null) log("this is a TextBox");

            it is both faster and more correct as it also matches derived types. :)

            Luc Pattyn [Forum Guidelines] [My Articles]


            I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


            modified on Saturday, November 28, 2009 7:37 AM

            C Offline
            C Offline
            c0ax_lx
            wrote on last edited by
            #5

            According to MSDN help -GetType and typeof returns System.Type, i totally agree with "if (sender is TextBox)". A humble question, do you mean that GetType()==typeof compiles as a string comparizon? else i dont understand the "do NOT compare strings to check for a type, instead use the appropriate keywords"

            If it' stuck, DO NOT pull harder!

            L 1 Reply Last reply
            0
            • C c0ax_lx

              According to MSDN help -GetType and typeof returns System.Type, i totally agree with "if (sender is TextBox)". A humble question, do you mean that GetType()==typeof compiles as a string comparizon? else i dont understand the "do NOT compare strings to check for a type, instead use the appropriate keywords"

              If it' stuck, DO NOT pull harder!

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #6

              Sorry, I should have said "do NOT compare types, nor strings representing types, to check for a type, ..." is/as are more efficient than GetType constructs :)

              Luc Pattyn [Forum Guidelines] [My Articles]


              I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


              C 1 Reply Last reply
              0
              • L Luc Pattyn

                Sorry, I should have said "do NOT compare types, nor strings representing types, to check for a type, ..." is/as are more efficient than GetType constructs :)

                Luc Pattyn [Forum Guidelines] [My Articles]


                I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


                C Offline
                C Offline
                c0ax_lx
                wrote on last edited by
                #7

                ok! Thanks Luc, for a split second i thought you were wrong, i should have known better ;)

                If it' stuck, DO NOT pull harder!

                P 1 Reply Last reply
                0
                • C c0ax_lx

                  ok! Thanks Luc, for a split second i thought you were wrong, i should have known better ;)

                  If it' stuck, DO NOT pull harder!

                  P Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #8

                  Ah, now that's signature material! :-D

                  L 1 Reply Last reply
                  0
                  • P PIEBALDconsult

                    Ah, now that's signature material! :-D

                    L Offline
                    L Offline
                    Luc Pattyn
                    wrote on last edited by
                    #9

                    :thumbsup:

                    Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                    I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


                    1 Reply Last reply
                    0
                    • I Islorvat

                      Hello! I'm working on an application wich will alow the user to add and remove controls. I want to apply different rules to textbox and this rules will be different for every textbox. For example i want to check wich control has been clicked by using a click event. Because i don't know how many textboxes will the user create i've decided to go along with the code below:

                          private void Form1\_Load(object sender, EventArgs e)
                          {
                              foreach (Control ctrl in Controls)
                              {
                                  ctrl.Click += new EventHandler(ctrl\_Click);
                              }
                          }
                      
                          void ctrl\_Click(object sender, EventArgs e)
                          {
                      
                          }
                      

                      Is there anyway that i can get the name of the control that has been clicked? The sender.Tostring() only returns the type and the text of the control. Thanks! ;)

                      B Offline
                      B Offline
                      BillWoodruff
                      wrote on last edited by
                      #10

                      Some ideas that may (I hope) bear on your solution : Is it the case that any TextBoxes are inside containers within the Form (nested) : in that case you are going to need to recurse to find them and attach an Event Handler. Unfortunately to get the Form.ControlCollection into a "flattened" IEnumerable where you can do cool filtering with Linq, and just, for example, pull out all the TextBoxes into a nice List<>, takes some voodoo which I am just now exploring myself, so am reluctant to comment on that so far. If TextBoxes are the only controls you want to put a special Event handler on, it seems like overkill to add a subscriber to the 'Click event of every control on your Form or whatever (unless, of course, they are all TextBoxes).

                              foreach (Control candidate in Controls)
                              {
                                  if(candidate is TextBox) // assign your event handler here
                              }
                      

                      The TextBox does expose an 'Enter event, and when that event is fired, you can be sure that the 'sender parameter inside that event is also the same as your MainForm.ActiveControl. That might be something you could exploit. If you are maintaining an arbitrary collection of TextBox controls which the end-user has the power to create and/or remove, you might consider keeping a List<TextBox> up to date, and, possibly a TextBox currentTextBox variable: these may come in handy. Assuming by "apply different rules to TextBoxes" you mean execute some code for one class of TextBoxes, and execute different code another class of TextBox you could consider a Dictionary of <TextBox, Action<Control>> as found in the very interesting answer by Nathan W. here : [^] which uses recursion in a very clever way. best, Bill

                      "Many : not conversant with mathematical studies, imagine that because it [the Analytical Engine] is to give results in numerical notation, its processes must consequently be arithmetical, numerical, rather than algebraical and analytical. This is an error. The engine can arrange and combine numerical quantities as if they were letters or any other general symbols; and it fact it might bring out its results in algebraical notation, were provisions made accordingly." Ada, Countess Lovelace, 1844

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups