【问题标题】:How to use array of textbox in button_click method?如何在 button_click 方法中使用文本框数组?
【发布时间】:2018-05-31 06:15:11
【问题描述】:

我在 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)
        {

        }

【问题讨论】:

  • 您应该在表单级别而不是在方法级别声明TextBox[] textBox1 = new TextBox[width_of_nonogram];TextBox[] textBox2 = new TextBox[height_of_nonogram];
  • 你应该阅读How to Ask,然后让你的问题更清楚。

标签: c# arrays winforms textbox


【解决方案1】:

您需要了解类字段和属性

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)

【讨论】:

    【解决方案2】:

    要访问文本框数组,您可以做的是:

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

    这样你就可以访问所有的文本框了,你可以做的是在 EnterColsAndRows 函数中为文本框指定名称并在上面的代码中使用它。

    【讨论】:

      猜你喜欢
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 2022-08-02
      • 2021-12-29
      相关资源
      最近更新 更多