0

At the moment, I have multiple textblocks which I want to access according to the name of the string. Look at the example below:

    TextBlock test1 = new TextBlock();
    TextBlock test2 = new TextBlock();
    TextBlock test3 = new TextBlock();
    TextBlock test4 = new TextBlock();

    public static void changeValues()
    {
        string name = "test";
        for (int i = 1; i < 5; i++)
        {
            [name + i].Text = "Wow";
        }
    }

As you can see, I am trying to access text1, text2, etc. The reason I am doing this is because the value of "name" could change at any time so I can re-use this code. I can also make "i < 5" be "i < number" and have the method take an int as one of the arguments. The problem of course is that this won't actually work. I need the string name to be a reference to the TextBlock that the name gives. Any help is appreciated!

4
  • 1
    Why not to use arrays instead? Commented Nov 4, 2016 at 1:08
  • Arrays of what and for why exactly? Commented Nov 4, 2016 at 1:09
  • Do you have problem with the line '[name + i].Text = "Wow"'? If so, you shouldn't access the control like this. Instead try, this.Controls[name +i].Text = "Wow"; Commented Nov 4, 2016 at 1:20
  • The name of a variable is completely arbitrary. It's all reduced to just values or memory addresses in the compiled code. As such, trying to build a "string name" of a variable is not only not possible, but is completely nonsensical. Commented Nov 4, 2016 at 1:44

2 Answers 2

2

@PetSerAl is saying:

var yourBlocks = new TextBlock[]
{
    new TextBlock(),
    new TextBlock(),
    new TextBlock(),
    new TextBlock()
};

foreach (var block in yourBlocks)
{
    block.Text = "Wow";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Put a breakpoint on the new TextBlock[] and step through in the debugger. As to your edit about using textblocks defined in XAML, put the names defined in the XAML in the new TextBlock[] { ... } instead of creating new ones.
0

How about Dictionary?

Dictionary<string, string> myDictionary= 
            new Dictionary<string, TextBlock>();
myDictionary.Add("name1", mytextBlock1);
myDictionary.Add("name2", mytextBlock2);
myDictionary["name1"] = new TextBlock();
var tBlock = myDictionary["name2"];

Detail here

1 Comment

Wouldn't that be creating a textblock based on a name. This isn't what I wanted to do.

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.