3

I have a 16 element int array and 16 textboxes (textBox1, textBox2 ....) that look like 4x4 matrix. Is there any way to put textboxes values to every array element not using code like this:

array[1] = (int)textBox1.Text;
array[2] = (int)textBox2.Text;
3
  • Nothing cleaner than that. You could use (this.FindControl("textBox" + i) as TextBox).Text but then you lose type safety Commented Sep 7, 2015 at 15:25
  • Agreeing with that above. Another possibility would be to set up an array of TextBox controls, like Control[] aTextBoxes = new Control[] { textBox1, textBox2, ..};, then looping through them with a for(int i=0; i < aTextBoxes.Length; i++) array[i] = Convert.ToInt32(aTextBoxes[i].Text); (complitly ommiting try-catch blocks or checking the length of the array first) Commented Sep 7, 2015 at 15:28
  • You better go with a proper naming of your controls or define an TextBox[] field in the form class. Also, there are things like jagged and rectangular/multidimensional arrays. Commented Sep 7, 2015 at 15:28

3 Answers 3

2

One possibility would be to store the references to the TextBox instances in an array.

TextBox[] Boxes;

And then use a 'for' loop to populate the values.

for (int i = 0; i < 16; i++)
{
   array[i] = (int)Boxes[i].Text;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could use a function to get the text box's text as an integer using it's "index" from the form's control collection:

int GetBoxText(int index)
{
  return Convert.ToInt32(this.Controls["textBox" + i.ToString()].Text);
}

Note that this has no error checking of any kind. You could add some if you wanted to. All this does is get the text of the control named textBox + whatever i is from the form's control collection and convert it to an integer.

Comments

0

IMHO the best way to design is by the way it's meant to be. In particular, rectangular/multidimensional arrays may be useful in this scenario:

public partial class Form1 : Form {
    TextBox[,] textBoxes;
    int[,] values;

    public Form1() {
        InitializeComponent();
        textBoxes = new TextBox[4, 4];
        values = new int[textBoxes.GetLength(0), textBoxes.GetLength(1)];
        for(int r = 0; r < textBoxes.GetLength(0); r++) {
            for(int c = 0; c < textBoxes.GetLength(1); c++) {
                values[r, c] = int.Parse(textBoxes[r, c].Text);
            }
        }
    }
}

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.