2013-03-16 41 views
0

我想要做的是,例如,如果我传递5作为matrSize那么它必须生成25个文本框,名为MatrixNode [11],.. MatrixNode [12] .. (就像在数学矩阵)这样Windows窗体根据给定的值动态生成文本框

enter image description here

的文本框将刚刚得到的矩阵元素,但默认情况下随机值将在右侧创建文本框后填写。

public partial class Form2 : Form 
    { 
     public Form2(int matrSize) 
     { 
      InitializeComponent(); 
      int counter=0; 
      TextBox[] MatrixNodes = new TextBox[matrSize*matrSize]; 
      for (int i = 0; i < matrSize; i++) 
      { 
       for (int j = 0; j < matrSize; j++) 
       { 
        var tb = new TextBox(); 
        Random r = new Random(); 
        int num = r.Next(1, 1000); 
        MatrixNodes[counter] = tb; 
        tb.Name = "Node_" + MatrixNodes[counter]; 
        tb.Text = num.ToString(); 
        tb.Location = new Point(172, 32 + (i * 28)); 
        tb.Visible = true; 
        this.Controls.Add(tb); 
        counter++; 
       } 
      } 
      Debug.Write(counter); 
     } 

现在的问题是:

  1. 我的函数填充同一号码生成的所有领域(不知道原因),实际上它必须是随机
  2. 外观必须完全一样数学中的矩阵,我的意思是,例如,如果我们传递值5,必须有5行和5列文本框。但我只能得到5个文本框垂直。

Thx提前。请帮忙找出函数

+0

建议使用DataGridView代替文本框。然后,您可以轻松遍历所有DataGridViewCells以读取值。例如:传递值5 - >向DataGridView添加5列和5行。您可以隐藏列和行的标题,它看起来像文本框。确定它在这种情况下更有效.... – Fabio 2013-03-16 16:39:00

回答

3
  1. 您正在创建的Random每个迭代一个新的实例,而这些都是在时间上非常接近,这就是为什么值相同。在之前创建一个实例外部for周期并且只需拨打Next()里面。

  2. 您所有的Point实例都具有相同的水平位置172,因此所有列都重叠。您需要使用j变量调整X,例如Point(172 + (j * 28), 32 + (i * 28))

+0

好的。 1个固定。 2怎么样? – heron 2013-03-16 09:55:40

+0

编辑我的答案也包括2。 – 2013-03-16 10:06:48

+0

如何命名文本框,我如何将它们命名为数学矩阵? – heron 2013-03-16 10:09:58

0

问题2:

要设置文本框的位置为:

tb.Location = new Point(172, 32 + (i * 28) 

,永不改变的X坐标(172),这样你只会得到一个列。

0
private void button1_Click(object sender, EventArgs e) 
{ 
    int matrSize = 4; 
    int counter = 0; 
    TextBox[] MatrixNodes = new TextBox[matrSize * matrSize]; 

    for (int i = 0; i < matrSize; i++) 
    { 
     for (int j = 0; j < matrSize; j++) 
     { 
      var tb = new TextBox(); 
      Random r = new Random(); 
      int num = r.Next(1, 1000); 
      MatrixNodes[counter] = tb; 
      tb.Name = "Node_" + MatrixNodes[counter]; 
      tb.Text = num.ToString(); 
      tb.Location = new Point(172 + (j * 150), 32 + (i * 50)); 
      tb.Visible = true; 
      this.Controls.Add(tb); 
      counter++; 
     } 

     counter = 0; 
    } 
}