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. Genericize access to variables

Genericize access to variables

Scheduled Pinned Locked Moved C#
question
25 Posts 20 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.
  • C Chris Trelawny Ross

    Here's a refinement that will only touch all labels you care about:

    foreach (Control control in Controls)
    {
    if (control is Label && label.Name.StartsWith("labelNamePrefixToModifyAsAGroup"))
    {
    ((Label)control).Text = "Something";
    }
    }

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #4

    Hax..

    1 Reply Last reply
    0
    • C Chris Trelawny Ross

      Here's a refinement that will only touch all labels you care about:

      foreach (Control control in Controls)
      {
      if (control is Label && label.Name.StartsWith("labelNamePrefixToModifyAsAGroup"))
      {
      ((Label)control).Text = "Something";
      }
      }

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

      which can be reduced to

      foreach (Control c in Controls) if (c.Name.StartsWith("labela")) c.Text = "Something";

      as every Control has a Name and a Text property. :)

      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

      Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

      C 1 Reply Last reply
      0
      • L Luc Pattyn

        which can be reduced to

        foreach (Control c in Controls) if (c.Name.StartsWith("labela")) c.Text = "Something";

        as every Control has a Name and a Text property. :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

        Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

        C Offline
        C Offline
        Chris Trelawny Ross
        wrote on last edited by
        #6

        Slaps self on head for missing that one. :doh:

        1 Reply Last reply
        0
        • D David Knechtges

          I googled this extensively yesterday and didn't come out with an answer: Is it possible to do some thing like this, and if so how? labela1.Text = "something"; labela2.Text = "something"; labela3.Text = "something"; Now what I want is a way to write that code as say: for (int i=1;i<4;i++) labelai.Text = "something"; so that the i in labelai above is replaced by 1, 2, 3 at runtime and the net result of the for loop is the same as what happens in the block above. Is there a way to do that? Thanks!

          realJSOPR Offline
          realJSOPR Offline
          realJSOP
          wrote on last edited by
          #7

          Reference parameters are your friend:

          private void SetLabelText(ref Label label, string text)
          {
          label.Text = text;
          }

          private void SomeFunction()
          {
          SetLabelText(ref label1, "something1");
          SetLabelText(ref label2, "something2");
          SetLabelText(ref label3, "something3");
          }

          .45 ACP - because shooting twice is just silly
          -----
          "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
          -----
          "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

          I 1 Reply Last reply
          0
          • realJSOPR realJSOP

            Reference parameters are your friend:

            private void SetLabelText(ref Label label, string text)
            {
            label.Text = text;
            }

            private void SomeFunction()
            {
            SetLabelText(ref label1, "something1");
            SetLabelText(ref label2, "something2");
            SetLabelText(ref label3, "something3");
            }

            .45 ACP - because shooting twice is just silly
            -----
            "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
            -----
            "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

            I Offline
            I Offline
            Ian Shlasko
            wrote on last edited by
            #8

            No need for 'ref', unless you want to change what the label1, label2, and label3 variables point to.

            Proud to have finally moved to the A-Ark. Which one are you in?
            Author of the Guardians Saga (Sci-Fi/Fantasy novels)

            1 Reply Last reply
            0
            • D David Knechtges

              I googled this extensively yesterday and didn't come out with an answer: Is it possible to do some thing like this, and if so how? labela1.Text = "something"; labela2.Text = "something"; labela3.Text = "something"; Now what I want is a way to write that code as say: for (int i=1;i<4;i++) labelai.Text = "something"; so that the i in labelai above is replaced by 1, 2, 3 at runtime and the net result of the for loop is the same as what happens in the block above. Is there a way to do that? Thanks!

              T Offline
              T Offline
              The Man from U N C L E
              wrote on last edited by
              #9

              for (int i=1;1<4;i++){
              this.Controls[string.Concat("labela", i.ToString())].Text = "something";
              }

              If you have knowledge, let others light their candles at it. Margaret Fuller (1810 - 1850) [My Articles]  [My Website]

              1 Reply Last reply
              0
              • D David Knechtges

                I googled this extensively yesterday and didn't come out with an answer: Is it possible to do some thing like this, and if so how? labela1.Text = "something"; labela2.Text = "something"; labela3.Text = "something"; Now what I want is a way to write that code as say: for (int i=1;i<4;i++) labelai.Text = "something"; so that the i in labelai above is replaced by 1, 2, 3 at runtime and the net result of the for loop is the same as what happens in the block above. Is there a way to do that? Thanks!

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #10

                No-one with a LINQ version yet?

                class Form1
                {
                IEnumerable<Control> summingLabels;

                public Form1()
                {
                InitializeComponent();
                
                summingLabels =
                	from c in Controls.Cast().AsQueryable()
                	where c.Name.StartsWith("sumLabel")
                	select c;
                
                // later on, when you need them
                foreach(Control l in summingLabels)
                	l.Text = l.Name;
                }
                

                }

                Keep a pointer around to the controls that you found; no need to iterate them every time :)

                I are Troll :suss:

                B 1 Reply Last reply
                0
                • D David Knechtges

                  I googled this extensively yesterday and didn't come out with an answer: Is it possible to do some thing like this, and if so how? labela1.Text = "something"; labela2.Text = "something"; labela3.Text = "something"; Now what I want is a way to write that code as say: for (int i=1;i<4;i++) labelai.Text = "something"; so that the i in labelai above is replaced by 1, 2, 3 at runtime and the net result of the for loop is the same as what happens in the block above. Is there a way to do that? Thanks!

                  D Offline
                  D Offline
                  Daniel Grunwald
                  wrote on last edited by
                  #11

                  The correct answer is: don't do that If you need multiple storage locations (variables) and access them by index, use an array. If you really have multiple variables (e.g. because they are generated by the VS forms designer), then you can still put those into an array:

                  Label[] labels = { labela1, labela2, labela3 };

                  P 1 Reply Last reply
                  0
                  • D Daniel Grunwald

                    The correct answer is: don't do that If you need multiple storage locations (variables) and access them by index, use an array. If you really have multiple variables (e.g. because they are generated by the VS forms designer), then you can still put those into an array:

                    Label[] labels = { labela1, labela2, labela3 };

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

                    Hear hear!

                    1 Reply Last reply
                    0
                    • D David Knechtges

                      I googled this extensively yesterday and didn't come out with an answer: Is it possible to do some thing like this, and if so how? labela1.Text = "something"; labela2.Text = "something"; labela3.Text = "something"; Now what I want is a way to write that code as say: for (int i=1;i<4;i++) labelai.Text = "something"; so that the i in labelai above is replaced by 1, 2, 3 at runtime and the net result of the for loop is the same as what happens in the block above. Is there a way to do that? Thanks!

                      P Offline
                      P Offline
                      Paul Michalik
                      wrote on last edited by
                      #13

                      David Knechtges wrote:

                      Is there a way to do that?

                      No, at least if I understand what you want... However, why would you want to do that? What's wrong with:

                      Label[] labela = {
                      labela0,
                      labela1,
                      labela2,
                      labela3,
                      };
                      //...
                      for (int i=0;i<4;i++)
                      labela[i].Text = "something";

                      modified on Wednesday, September 1, 2010 5:55 PM

                      A 1 Reply Last reply
                      0
                      • P Paul Michalik

                        David Knechtges wrote:

                        Is there a way to do that?

                        No, at least if I understand what you want... However, why would you want to do that? What's wrong with:

                        Label[] labela = {
                        labela0,
                        labela1,
                        labela2,
                        labela3,
                        };
                        //...
                        for (int i=0;i<4;i++)
                        labela[i].Text = "something";

                        modified on Wednesday, September 1, 2010 5:55 PM

                        A Offline
                        A Offline
                        AspDotNetDev
                        wrote on last edited by
                        #14

                        This answer was already posted hours ago.

                        [Forum Guidelines]

                        1 Reply Last reply
                        0
                        • D David Knechtges

                          I googled this extensively yesterday and didn't come out with an answer: Is it possible to do some thing like this, and if so how? labela1.Text = "something"; labela2.Text = "something"; labela3.Text = "something"; Now what I want is a way to write that code as say: for (int i=1;i<4;i++) labelai.Text = "something"; so that the i in labelai above is replaced by 1, 2, 3 at runtime and the net result of the for loop is the same as what happens in the block above. Is there a way to do that? Thanks!

                          L Offline
                          L Offline
                          Lukasz Nowakowski
                          wrote on last edited by
                          #15

                          You can also try reflection if you really really really really really really really really must do it this way and not using array/collection (depending on a situation).

                          Don't forget to rate answer, that helped you. It will allow other people find their answers faster.

                          1 Reply Last reply
                          0
                          • D David Knechtges

                            I googled this extensively yesterday and didn't come out with an answer: Is it possible to do some thing like this, and if so how? labela1.Text = "something"; labela2.Text = "something"; labela3.Text = "something"; Now what I want is a way to write that code as say: for (int i=1;i<4;i++) labelai.Text = "something"; so that the i in labelai above is replaced by 1, 2, 3 at runtime and the net result of the for loop is the same as what happens in the block above. Is there a way to do that? Thanks!

                            A Offline
                            A Offline
                            Alexander Voronin
                            wrote on last edited by
                            #16

                            Try to use this construction:

                            this.GetType().GetField("variablename")

                            This should work for c# but better try to avoid such kind of code. Other languages has different RTTI, for example in c/c++ this is impossible at all.

                            1 Reply Last reply
                            0
                            • D David Knechtges

                              I googled this extensively yesterday and didn't come out with an answer: Is it possible to do some thing like this, and if so how? labela1.Text = "something"; labela2.Text = "something"; labela3.Text = "something"; Now what I want is a way to write that code as say: for (int i=1;i<4;i++) labelai.Text = "something"; so that the i in labelai above is replaced by 1, 2, 3 at runtime and the net result of the for loop is the same as what happens in the block above. Is there a way to do that? Thanks!

                              E Offline
                              E Offline
                              ExportedNorwegian
                              wrote on last edited by
                              #17

                              Not sure about the performance implications of FindControl.. But this one is pretty close to what you originally wrote

                              for (int i=1;i<4;i++)
                              (Controls.FindControl("labela" + i.ToString()) as Label).Text = "something";

                              1 Reply Last reply
                              0
                              • L Lost User

                                No-one with a LINQ version yet?

                                class Form1
                                {
                                IEnumerable<Control> summingLabels;

                                public Form1()
                                {
                                InitializeComponent();
                                
                                summingLabels =
                                	from c in Controls.Cast().AsQueryable()
                                	where c.Name.StartsWith("sumLabel")
                                	select c;
                                
                                // later on, when you need them
                                foreach(Control l in summingLabels)
                                	l.Text = l.Name;
                                }
                                

                                }

                                Keep a pointer around to the controls that you found; no need to iterate them every time :)

                                I are Troll :suss:

                                B Offline
                                B Offline
                                BC3Tech
                                wrote on last edited by
                                #18

                                how about lambda? :)

                                foreach (Control l in Controls.Cast().Where(c => c.Name.StartsWith("sumLabel")))
                                l.Text = l.Name;

                                L 1 Reply Last reply
                                0
                                • D David Knechtges

                                  I googled this extensively yesterday and didn't come out with an answer: Is it possible to do some thing like this, and if so how? labela1.Text = "something"; labela2.Text = "something"; labela3.Text = "something"; Now what I want is a way to write that code as say: for (int i=1;i<4;i++) labelai.Text = "something"; so that the i in labelai above is replaced by 1, 2, 3 at runtime and the net result of the for loop is the same as what happens in the block above. Is there a way to do that? Thanks!

                                  D Offline
                                  D Offline
                                  Dave Buhl
                                  wrote on last edited by
                                  #19

                                  This is not exactly what you were asking for but is an alternative using binding. This may be overkill for what you are trying to do but it would be more elegant. Bind your labels as you create them to an object of a class that implements INotifyChanged then when you change the property of the object each label will be updated without having to work loops. http://stackoverflow.com/questions/639894[^] Dave

                                  1 Reply Last reply
                                  0
                                  • D David Knechtges

                                    I googled this extensively yesterday and didn't come out with an answer: Is it possible to do some thing like this, and if so how? labela1.Text = "something"; labela2.Text = "something"; labela3.Text = "something"; Now what I want is a way to write that code as say: for (int i=1;i<4;i++) labelai.Text = "something"; so that the i in labelai above is replaced by 1, 2, 3 at runtime and the net result of the for loop is the same as what happens in the block above. Is there a way to do that? Thanks!

                                    J Offline
                                    J Offline
                                    JaceTheAce
                                    wrote on last edited by
                                    #20

                                    Array.ForEach(new Control[] { labela1, labela2, labela3 }, delegate(Control c) { c.Text = "something"; });

                                    1 Reply Last reply
                                    0
                                    • B BC3Tech

                                      how about lambda? :)

                                      foreach (Control l in Controls.Cast().Where(c => c.Name.StartsWith("sumLabel")))
                                      l.Text = l.Name;

                                      L Offline
                                      L Offline
                                      Lost User
                                      wrote on last edited by
                                      #21

                                      Lambda's look cool :cool: It's either searching through the collection and keeping the result around, or hardcoding them in advance. Attributes that mark a set of fields as a group might be another option, but that would add a bit more complexity. No, I think I like the lambda better. Would also be cool combined with a regex :) Nearly forgot, but that cast in my original query would be redundant, as we'd only need to store labels;

                                      class Form1
                                      {
                                      IEnumerable summingLabels;
                                      public Form1()
                                      {
                                      InitializeComponent();

                                      	summingLabels =
                                      		from c in Controls.Cast().AsQueryable()
                                      		where c.GetType() == typeof(Label)
                                      		&& c.Name.StartsWith("label")
                                      		select c as Label;
                                      
                                      	// later on, when you need them
                                      	foreach(Label l in summingLabels)
                                      		l.Text = l.Location.ToString();
                                      }
                                      

                                      }

                                      I are Troll :suss:

                                      S 1 Reply Last reply
                                      0
                                      • L Lost User

                                        Lambda's look cool :cool: It's either searching through the collection and keeping the result around, or hardcoding them in advance. Attributes that mark a set of fields as a group might be another option, but that would add a bit more complexity. No, I think I like the lambda better. Would also be cool combined with a regex :) Nearly forgot, but that cast in my original query would be redundant, as we'd only need to store labels;

                                        class Form1
                                        {
                                        IEnumerable summingLabels;
                                        public Form1()
                                        {
                                        InitializeComponent();

                                        	summingLabels =
                                        		from c in Controls.Cast().AsQueryable()
                                        		where c.GetType() == typeof(Label)
                                        		&& c.Name.StartsWith("label")
                                        		select c as Label;
                                        
                                        	// later on, when you need them
                                        	foreach(Label l in summingLabels)
                                        		l.Text = l.Location.ToString();
                                        }
                                        

                                        }

                                        I are Troll :suss:

                                        S Offline
                                        S Offline
                                        Shani Natav
                                        wrote on last edited by
                                        #22

                                        Or Maybe to make it nicer with no casting and type checking:

                                        summingLabels =
                                        from c in Controls.OfType()
                                        where c.Name.StartsWith("label")
                                        select c;

                                        	// later on, when you need them
                                        	foreach(Label l in summingLabels)
                                        		l.Text = l.Location.ToString();
                                        
                                        L 1 Reply Last reply
                                        0
                                        • S Shani Natav

                                          Or Maybe to make it nicer with no casting and type checking:

                                          summingLabels =
                                          from c in Controls.OfType()
                                          where c.Name.StartsWith("label")
                                          select c;

                                          	// later on, when you need them
                                          	foreach(Label l in summingLabels)
                                          		l.Text = l.Location.ToString();
                                          
                                          L Offline
                                          L Offline
                                          Lost User
                                          wrote on last edited by
                                          #23

                                          Yup, works, and more concise and readable :thumbsup:

                                          I are Troll :suss:

                                          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