Add TextBox.Text to a list using a for loop

后端 未结 3 1470
再見小時候
再見小時候 2021-01-23 19:25

I am trying to take the values in the textboxes, named sequentially from 0-9, and add that to a List using a for loop. I am having problems with the syntax or something.

相关标签:
3条回答
  • 2021-01-23 19:28

    I suppose that your textbox are named "amtBox" + a number. (The Name property is "amtBox1" as an example)

    In this case you could use

     Control[] t = Controls.Find("amtBox" + i, false);
    

    for a code like this

    for (int i = 0; i <= amt.Count(); i++)  
    {  
        Control[] t = Controls.Find("amtBox" + i, false);
        if(t != null && t.Length > 0)
        {
            amt[i] = int.Parse(t[0].Text);  
        }
    } 
    
    0 讨论(0)
  • 2021-01-23 19:33

    My understanding is that you have text boxes named amtBox1, amtBox2, etc., and what you are trying to do is sequence through them. As you point out, this is very easy in PHP. It is possible to do what you're suggesting using reflection, but that is expensive and, in any event, there's probably a better way to do what you're looking for.

    You could put all of your amount boxes into an array, and then what you have would work:

    var amtBoxes = new[] {
        amtBox1,
        amtBox2,
        amtBox3
    }
    
    0 讨论(0)
  • 2021-01-23 19:54

    One solution would be to declare an array and assign amtBox'es to the individual indexes in the array and then you can iterate on that array.

    var amtBoxes = new TextBox[] { amtBox0, amtBox1, .... };
    for (int i = 0; i <= amt.Count(); i++)
    {
        amt[i] = int.Parse(amtBoxes[i].Text);
    }
    

    If you end up needing to iterate on your TextBox controls in other places I would consider making the array an instance member of your object.

    0 讨论(0)
提交回复
热议问题