2011-02-08 114 views
0

你好全部 我真的需要你的帮助,我在大学的最后一个项目
我必须制作矩阵的文本框,用户可以选择它的大小 但我不知道我创建它后我如何引用文本框所以我可以做计算 ,我该如何改变类型。 ,这是我提出来获得在运行时的文本框代码 我希望你帮我 C#代码如何从动态文本框中获取值?

private void button1_Click(object sender, EventArgs e) 
    { 

     //TextBox tb = new TextBox(); 

     int y = 10; 
     row = Convert.ToInt32(textBox1.Text); 
     int col = row; 
     //string []a = new string[row]; 
     int count = 0; 
     int sum; 
     for (int i = 0; i < row; i++) 
     { 
      int x = 10; 

      for (int j = 0; j < col; j++) 
      { 
       t = new TextBox(); 
       t.Size = new Size(50, 20); 
       t.Name = "tb" + count; 
       count++; 
       t.Location = new Point(x, y); 
       t.Visible = true; 


       //t.GetType(); 
       //a[row] = t.Text; 

       Controls.Add(t); 
       x = x + 70; 
       //t.Text =Convert.ToDecimal(t.Text); 
       //Convert.ToDecimal(t.Text); 
       if (t.Name == "tb1") 
        t.Text = "10"; 
      } 
      y = y + 25; 
     } 

回答

1

保持一个参考各TextBox(你可以将其存储在一个二维数组为例):

// Defined at the Form level 
private TextBox[,] textBoxes = new TextBox[10, 10]; 

... 

// When creating the TextBox 
t = new TextBox(); 

... 

// Store the reference 
textBoxes[i, j] = t; 

... 

以后就可以得到价值:

var text = textBoxes[row, col].Text; 
+0

非常感谢你,我希望你更新我的网页,如果我有其他问题 – user607631 2011-02-08 06:17:28

1

名称添加到您的新插入文本框:

t.Name = "dynamicTextBox" + i.ToString(); 

之后,你可以简单地通过它的名称来访问它:

this.Controls["dynamicTextBox0"].Text = "my text"; 

这避免了需要额外的数组来保存动态创建文本框。

0

尝试此,

文本框T =(文本框)控制[ “TB” + count.ToString()]

的contorl的name属性变为控制集合中的密钥。

另外你可以检查Controls.ContainsKey(“TB” + count.ToString())生存

相关问题