0

我正在根据用户选择(1-5)创建几个文本框。当文本更改时,如何访问编程文本框的值。

class starts{
    int i=0;

    .....

    TextBox txtb4 = new TextBox();
    txtb4.Name = "textname" + Convert.ToString(i);
    ArrayText.Add(txtb4);
    System.Drawing.Point p5 = new System.Drawing.Point(120, 15);
    txtb4.Location = p5;
    txtb4.Size = new System.Drawing.Size(80, 30);
    txtb4.Text = stringMy;
    grBox1.Controls.Add(txtb4);
    i++;
}

我可以使用下面的代码访问初始文本框文本,但在更改值后我无法访问它。

label15.Text = grBox1.Controls["textname0"].Text;
4

2 回答 2

4

所以,像...

TextBox txtb4 = new TextBox();
txtb4.Name = "textname" + Convert.ToString(i);
txtb4.TextChanged += textbox_TextChanged;
ArrayText.Add(txtb4);

// ...

void textbox_TextChanged(object sender, EventArgs e)
{
    var textbox = (TextBox)sender;
    // work with textbox
}
于 2012-05-02T17:21:16.563 回答
2

添加事件处理程序

txtb4.TextChanged += Txtb4_TextChanged;

像这样声明处理程序

static void Txtb4_TextChanged(object sender, EventArgs e)
{
    string s = txtb4.Text;
    ...
}    

您动态创建文本框;但是您的代码看起来不是很动态。尝试这个

List<TextBox> _textBoxes = new List<TextBox>();
int _nextTextBoxTop = 15;

private void AddTextBox(string initialText)
{
    var tb = new TextBox();
    tb.Name = "tb" + _textBoxes.Count;
    _textBoxes.Add(tb);
    tb.Location = new Point(120, _nextTextBoxTop);
    _nextTextBoxTop += 36;
    tb.Size = new Size(80, 30);
    tb.Text = initialText;
    tb.TextChanged += TextBox_TextChanged
    grBox1.Controls.Add(tb);
}

static void TextBox_TextChanged(object sender, EventArgs e)
{
    TextBox tb = (TextBox)sender;
    string s = tb.Text;
    ...
}    

而且我不会通过grBox1.Controls["textname0"].Text;. 文本框列表是更好的选择,因为您可以通过数字索引而不是控件名称来访问它

string s = _textBoxes[i].Text;
于 2012-05-02T17:22:18.570 回答