syn3rgy syn3rgy - 1 month ago 8
C# Question

Loop and Array - Show Strings

I am trying to show a group variables that contains a string from the code behind (C#) to Textblock in XAML using the code below:

Textblock1.Text = String1Class;
Textblock2.Text = String2Class;
Textblock3.Text = String3Class;
Textblock4.Text = String4Class;
Textblock5.Text = String5Class;
Textblock6.Text = String6Class;


The code works but its a pain writing the same thing over and over again.
I want to ask if there is a better way. I know it has to do with arrays and loops, but I am not very familiar with C# and WPF.

Answer

Given the fact that you have separate variables for each of the StringXClass values you need to do this if you want to keep the variables the same:

var tbs = new [] { Textblock1, Textblock2, Textblock3, Textblock4, Textblock5, Textblock6, };
var scs = new [] { String1Class, String2Class, String3Class, String4Class, String5Class, String6Class, };

for (var i = 0; i < tbs.Length; i++)
{
    tbs.Text = scs;
}

The alternative is to set up an array in the first place.

var StringClass = new string[6];

Then replace String1Class with StringClass[0], String2Class with StringClass[1], etc, in your code.

Then write this:

var tbs = new [] { Textblock1, Textblock2, Textblock3, Textblock4, Textblock5, Textblock6, };
for (var i = 0; i < tbs.Length; i++)
{
    tbs.Text = StringClass[i];
}