How can I get values from dynamic TextBox?
hello all i really need your help its my final project in university
i have to make matrix of text boxs that the user chosse the size of it but i dont know after i create it how do i refer to the textbox so i can do the calculation and how do i change the type . thats the c开发者_如何学Goode i made to get textbox at run time i hope you help me C# codeprivate 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;
}
Keep a reference to each TextBox
(you can store it in a two-dimension array, for example):
// 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;
...
Later you can get the value:
var text = textBoxes[row, col].Text;
Add a name to your newly inserted textboxes:
t.Name = "dynamicTextBox" + i.ToString();
After that, you can simply access it via its name:
this.Controls["dynamicTextBox0"].Text = "my text";
This prevents the need for an extra array to hold the textboxes you create dynamically.
try this,
TextBox t = (TextBox)Controls["tb"+count.ToString()]
the name property of the contorl becomes the key in the control collection.
additionally you can check for Controls.ContainsKey("tb"+count.ToString()) for existence
精彩评论