如何在button_click方法中使用文本框数组?

时间:2018-05-31 06:15:11

标签: c# arrays winforms textbox

我在EnterColsAndRows类中创建了一系列行和列的文本框。我需要在button_click方法中使用它来为每个行和列创建一个int变量数组。

public partial class EnterColsAndRows : Form
    {
        public  int width_of_nonogram;
        public  int height_of_nonogram;
        public EnterColsAndRows(int width, int height)
        {
            InitializeComponent();
            width_of_nonogram = width;
            height_of_nonogram = height;
            TextBox[] textBox1 = new TextBox[width_of_nonogram];
           TextBox[] textBox2 = new TextBox[height_of_nonogram];
            for (int i = 0; i < width_of_nonogram; i++)
            {
                textBox1[i] = new TextBox();
                textBox1[i].Text = "Col " + (i + 1);
                Point p = new Point(20, 30 * i);
                textBox1[i].Location = p;
                this.Controls.Add(textBox1[i]);
            }

            for (int i = 0; i < height_of_nonogram; i++)
            {
                textBox2[i] = new TextBox();
                textBox2[i].Text = "Row " + (i + 1);
                Point p = new Point(200, 30 * i);
                textBox2[i].Location = p;
                this.Controls.Add(textBox2[i]);

            }

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

2 个答案:

答案 0 :(得分:0)

您需要了解类字段和属性

private TextBox[] textBox1;
private TextBox[] textBox2;;

...
public EnterColsAndRows(int width, int height)
{

    ...

    textBox1 = new TextBox[width_of_nonogram];
    textBox2 = new TextBox[height_of_nonogram];

    ...

}

private void button1_Click(object sender, EventArgs e)
{
    if(textBox1 != null && textBox1.Length > 0)
    {
        textBox1[0].Text = "Awesome, i am"
    }
}

进一步阅读

Classes (C# Programming Guide)

Fields (C# Programming Guide)

答案 1 :(得分:0)

要访问文本框数组,您可以执行以下操作:

foreach (Control x in this.Controls)
{
  if (x is TextBox)
  {
    var textbox = ((TextBox)x);//Your code goes here.
  }
}

通过这个,您将能够访问所有文本框,您可以做的是为EnterColsAndRows函数中的文本框指定名称,并在上面的代码中使用它。