Textbox values to array

2019-09-01 02:36发布

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条回答
太酷不给撩
2楼-- · 2019-09-01 03:19

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();
查看更多
倾城 Initia
3楼-- · 2019-09-01 03:22

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";
}
查看更多
Emotional °昔
4楼-- · 2019-09-01 03:34

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.

查看更多
老娘就宠你
5楼-- · 2019-09-01 03:37

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();
查看更多
成全新的幸福
6楼-- · 2019-09-01 03:39

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
}
查看更多
登录 后发表回答