swenflea
swenflea

Reputation: 572

Use an int when accessing a name in C#

I'm currently build a windows phone 8 application using c# and I'm wondering how I can achieve this:

for (int i = 1; i <= 18; i++)
{
    _(i)Score.Text = "whatever here";
}

which when run should be something like:

_1Score.Text = "whatever here";
_2Score.Text = "whatever here";
_3Score.Text = "whatever here";
etc.

How am I able to achieve this as just putting _(i)Score doesn't work.

EDIT: What im doing is making a scorecard app which has a table overview. I've named each one as 1Socre, 2Score, 3Score etc. and I just want to update what they say. They are all textboxes and I'm just replacing the text inside.

Please Help. Thanks

Upvotes: 0

Views: 76

Answers (1)

Austin Salonen
Austin Salonen

Reputation: 50235

This most direct way to implement what you're doing:

var name = string.Format("_{0}Score", i);
this.Controls[name].Text = "...";

Knowing the types (based on @sa_ddam213's comment):

foreach(var textBox in Children.OfType<TextBox>().Where(txt => txt.Name.EndsWith("Score")))
{
    textBox.Text = "...";
}

Upvotes: 5

Related Questions