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 rig开发者_StackOverflowht?
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) {
}
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;
}
Put the controls into an array and then iterate the array.
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();
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);
//...
}
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);
精彩评论