How to encode names in C #

I have 10 text fields, namely TB1, TB2, TB3, TB4, etc. on TB10

I want to save them in a single string value with a name in BeStored.

Now i do the manual way

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

etc.

I want to create a for loop and add them

something like that..

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

I know this is wrong .. everything to do it right?

+3
source share
6 answers

No. Since you defined text fields as variables, there is simply no enumerator.

You can define your own counter. In the simplest case, which is as simple as

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

foreach (TextBox box in boxes) {
}
+3
source

Although I think the premise may be wrong, you can do it with

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

, .

+1

, , winforms, webforms . .

Secondly, you probably do not need to use .ToString () in the Text property, which I would assume is already a string.

Finally, if you insist on laziness, add the text fields to the array and go through 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();
+1
source

You can use reflection at all if you want to get the 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);
    //...
}
+1
source

If this were done, I would create a helper method for accumulating text into a string.

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

which will be called similar

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

0
source

Source: https://habr.com/ru/post/1763004/


All Articles