Textbox values to array

旧时模样 提交于 2019-12-13 06:51:25

问题


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?


回答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.




回答2:


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



回答3:


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
}



回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/8022724/textbox-values-to-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!