i've got a few Textboxes and I want to loop through them and check if they contain a value, and if they do, put it into an array.
The textboxes are called txtText1, txtText2....txtText12.
This is what I got so far:
for (int i = 1; i < 13; i++)
{
if(txtText[i] != String.Empty)
{
TextArray[i] = Convert.ToString(txtText[i].Text);
}
}
..but txtText[i] is not allowed.
How can I loop through these boxes?
Ideally, by putting them in an array to start with, instead of using several separate variables. Essentially you want a collection of textboxes, right? So use a collection type.
You could use
TextBox tb = (TextBox) Controls["txtText" + i];
assuming their IDs have been specified correctly, but personally I would use the collections designed for this sort of thing.
Assuming the txtText array contains references to TextBox objects you can do this
var textArray=txtText.Where(t=>!string.IsNullOrEmpty(t.Text)).Select(t=>t.Text).ToArray();
I don't think you can make array objects like that anymore in the designer.
Anyway what you can do: you can make a class variable IEnumerable<Textbox> _textboxes
, and fill it with all textboxes in the constructor.
then later in your code you can just do
foreach(var textbox in _textboxes)
{
Console.WriteLine(textbox.Text); // just an example, idk what you want to do with em
}
you can try like this....
List<string> values = new List<string>();
foreach(Control c in this.Controls)
{
if(c is TextBox)
{
TextBox tb = (TextBox)c;
values.Add(tb.Text);
}
}
string[] array = values.ToArray();
Try creating a list of textboxes instead of an Array like this:
List<TextBox> myTextboxList = new List<TextBox>();
myTextBoxList.Add(TextBox1);
myTextBoxList.Add(TextBox2);
mytextBoxList.Add(TextBox3);
Then use a foreach to access every item at once like this:
Foreach (TextBox item in myTextboxList) {
// Do something here, for example you can:
item.Text = "My text goes here";
}