0

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?

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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();

Comments

0

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
}

Comments

0

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();

Comments

0

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";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.