william
william

Reputation: 7664

How To loop the names in C#

I have 10 text boxes namely TB1, TB2, TB3, TB4 and so on.. to TB10

I want to store them into a single string value named toBeStored.

Now I m doing the manual way

String toBeStored=null;
tobeStored=TB1.text.toString();
tobeStored+=TB2.text.toString();

and so on..

I want to make a for loop and add them

something like this..

for(int i=1;i<11;i++)
{
      toBeStored+=TB+i+.text.ToString()+"  ";
}

I know that is wrong.. anything to make it right?

Upvotes: 3

Views: 393

Answers (6)

David Culp
David Culp

Reputation: 5480

If was to do such a thing I would create a helper method to accumulate the text into a string.

    public string AccumulateNames(params string[] names)
    {
        return names.Aggregate(string.Empty, (current, name) => current + name);
    }

which would be called similar to this

var toBeStored = AccumulateNames(TB1.Text, TB2.Text, ..., TBn.Text);

Upvotes: 0

Jeff Mercado
Jeff Mercado

Reputation: 134891

You can use reflection in general if you want to get a field by name.

Type type = GetType();
for (int i = 1; i <= 10; i++)
{
    var name = "TB" + i;
    var field = type.GetField(name, BindingFlags.Instance | BindingFlags.NonPublic); //or appropriate flags
    TextBox tb = (TextBox)field.GetValue(this);
    //...
}

Upvotes: 1

TomTom
TomTom

Reputation: 62101

No. Because you defined the text boxes as variables there simply is no enumerator defined.

You could define your own enumerator. In the simpliest case that is as simple as

TextBox boxes [] = new TextBox [] { TB1, TB2, TB3....}

foreach (TextBox box in boxes) {
}

Upvotes: 3

John Saunders
John Saunders

Reputation: 161783

First of all, you didn't tell us whether you're using winforms, webforms, or what. That would be good.

Second, you probably don't need to use .ToString() on the Text property, which I would assume is already a string.

Finally, if you insist on being lazy, then put the text boxes into an array, and loop over the array:

private TextBox[] _textBoxes = new TextBox[10];

// In init code:
TextBox[0] = TB1;
TextBox[1] = TB2;
// ...

StringBuilder toBeStored = new StringBuilder();
for (int i=0; i<10; i++)
{
   toBeStored.Append(TextBox[i].Text);
}

// Now process toBeStored.ToString();

Upvotes: 1

jcolebrand
jcolebrand

Reputation: 16035

While I think the premise may be flawed, you could do this by

for (int i = 1; i <= 10 ; i++) {
  TextBox textbox = (TextBox)Page.FindControls( "TB" + i.ToString);
  toBeStored += textbox.Text;
}

Upvotes: 2

Preet Sangha
Preet Sangha

Reputation: 65516

Put the controls into an array and then iterate the array.

Upvotes: 1

Related Questions