Use a string to call a variable in C #

I am trying to use a loop to edit data from several text fields, but I cannot figure out how to convert a string whose contents are the name of my window to access the text element of each window.

private void reset_Click(object sender, EventArgs e) { string cell; for(int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { cell = "c" + Convert.ToChar(i) + Convert.ToChar(j); cell.text = ""; } } 

My text fields are called "c00, c01, ... c87, c88", which will contain the contents of my "mesh" variable during each iteration, however, the above code does not work because it tries to access the "text" element of the string which obviously does not make sense.

Obviously, I can clear the contents of each window separately, but since I will have several events that change the contents of the text fields, it would be ideal to be able to implement a loop to do this, and not have 81 lines for each event.

+4
source share
3 answers

It is much better to use an array. Or a 2D array like this:

 TextBox[,] textboxes = ... private void reset_Click(object sender, EventArgs e) { for(int i = 0; i < textboxes.GetLength(0); i++) { for (int j = 0; j < textboxes.GetLength(1); j++) { textboxes[i,j].Text = ""; } } } 

Or a jagged array like this:

 TextBox[][] textboxes = ... private void reset_Click(object sender, EventArgs e) { for(int i = 0; i < textboxes.Length; i++) { for (int j = 0; j < textboxes[i].Length; j++) { textboxes[i][j].Text = ""; } } } 
+8
source

I recommend using a two-dimensional array of TextBoxes. It will make your life easier.

Anyway, try this.Controls.Find()

+5
source

You should be able to linq to it.

 TextBox txtBox = this.Controls.Select( c => c.Name == cell ); txtBox.Text = ""; 
+1
source

Source: https://habr.com/ru/post/1498870/


All Articles