2013-03-16 66 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; 
    } 
}