Search code examples
c#textbox

Is there a way to read multiple textboxes within a for C#


Is there a better way of doing this block of code? I want it inside of a for

            points[0] = Convert.ToDouble(textBox1.Text);
            points[1] = Convert.ToDouble(textBox2.Text);
            points[2] = Convert.ToDouble(textBox3.Text);
            points[3] = Convert.ToDouble(textBox4.Text);
            points[4] = Convert.ToDouble(textBox5.Text);
            points[5] = Convert.ToDouble(textBox6.Text);
            points[6] = Convert.ToDouble(textBox7.Text);
            points[7] = Convert.ToDouble(textBox8.Text);

The index [i] does not work within textBox[i].Text

for(int i = 0; i < points.Length; i++)
            {
                points[i] = Convert.ToDouble(textBox[i].Text);
            } 

Solution

  • You can write this adding a using Linq;

    var points = new [] { textBox1, textBox2, textBox3, textBox4, textBox5,textBox6, textBox7}
                        .Select(x => double.Parse(x.Text)).ToArray();
    

    This will create an array from your textboxes then on this sequence we apply the Select extension to enumerate each element and parsing its content to a double. The resulting sequence is finally converted to an array.

    Of course this assumes a lot about the conversion in double of your inputs and the correctness of your inputs. If you are not sure about the presence of characters that represent a double value in your inputs then you need a more traditional approach, adding a check in the conversion process.

    List<double> p = new List<double>();
    var tb = new []{ textBox1, textBox2, textBox3, textBox4,
                     textBox5, textBox6, textBox7,};
    
    for(int i = 0; i < tb.Length; i++)
       if(double.TryParse(tb[i].Text, out double temp))
           p.Add(temp);
    
    var points = p.ToArray();