0

i'm writing a program in C# , which contains a dozen toolstrips and each one contains a toolstriplabel :

toolstriplabel1 toolstriplabel2 toolstriplabel3 . . . toolstriplabel11 toolstriplabel12

i want to change each ones text with a "for" loop , how can i do that?? i can use "if" with other variables to meet this , but i want to avoid the dozen "if"s i have to write. How Can i use a "for" loop with toolstriplabel's , text property? i tried using this code , it doesn't work :

    for (int r = 0; r < NumGraphs; r++)
    { 
       toolStripLabel+"i".text=...
    }
3
  • And this happens to be which language? JS? Commented Jul 22, 2014 at 5:26
  • yup, forgot that , sorry , C# Commented Jul 22, 2014 at 5:27
  • yes it is windows Forms Commented Jul 22, 2014 at 6:18

3 Answers 3

1

You can simply try something like this,

        foreach (Control ctr in this.Controls)
        {
            if (ctr is ToolStripLabel)
            {
              // ur code
            }
        }
Sign up to request clarification or add additional context in comments.

3 Comments

I find using of var label = ctr as ToolStripLabel; followed by if (ctr != null) { ... } more pleasant. Instead of asking on a type I directly cast to the type, because you will need to do it later anyway.
this would work if i wanted to apply a single value to all of them not if i want them to be specified each seperately
@Hitman2847 It's probably caused by asking the question the wrong way. Now I see that you are asking how to change their text without a bunch of if statements, but it actually seems like you are just having troubles with looping through them. You should express your question better so that it's clear what are all the problems you need to solve.
0

Not familiar with C# but You can create an array of these toolStrips. In for loop, set the text property of the ith element in the array at ith iteration.

  for (int i = 0; i < NumGraphs; i++) { 
         toolStripLabel[i].text="YOUR TEXT";
  }

3 Comments

well that's easy but it didn't come to my mind ,thanks , but that also requires all 12 elements declare seperately , isn't there any way using for directly on the object?
Sorry, I am not familiar with C#.
thanx anyway , at least i know how to do it indirectly
0

What about using LINQ on collection of controls?

var labels = this.Controls.Cast<Control>()
                 .OfType<ToolStripLabel>()
                 .Where(l => l.Name.Contains("toolstriplabel"));

Then you can simply loop through them with a foreach loop.

foreach (var label in labels) { label.Text = ""; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.