1

我有一个关于 C# 中的文本框的问题。我制作了一个按钮,单击时将创建文本框:

    private void helloButton_Click(object sender, EventArgs e)
    {
        TextBox txtRun = new TextBox();
        TextBox txtRun2 = new TextBox();
        txtRun2.Name = "txtDynamic2" + c++;
        txtRun.Name = "txtDynamic" + c++;
        txtRun.Location = new System.Drawing.Point(40, 50 + (20 * c));
        txtRun2.Location = new System.Drawing.Point(250, 50 + (20 * c));
        txtRun2.ReadOnly = true;

        txtRun.Size = new System.Drawing.Size(200, 25);
        txtRun2.Size = new System.Drawing.Size(200, 25);
        this.Controls.Add(txtRun);
        this.Controls.Add(txtRun2);
    }

如何将用户键入的文本拉入这些新生成的文本框中,以将其用作不同函数的参数(将由不同的按钮调用)?我对此很陌生,可以使用帮助。

提前致谢。

4

4 回答 4

1
var text = (TextBox)this.Controls.Find("txtDynamic2", true)[0];
于 2013-02-09T10:56:38.607 回答
1
var matches = this.Controls.Find("txtDynamic2", true);
TextBox tx2 = matches[0] as TextBox;            
string yourtext = tx2.Text;

This will return an array of controls by the name txtDynamic2, in your case the first one would be the control you are looking for unless you create more controls having the same name. This will allow you to fully access the textbox if you found it.

于 2013-02-09T10:25:24.817 回答
0

你可以很容易地做到这一点:

//get the text from a control named "txtDynamic"
string text = this.Controls["txtDynamic"].Text;

请记住确保您的控件具有唯一 Name属性,否则您将从找到的第一个具有指定名称的控件中获取文本。

于 2013-02-09T10:38:15.317 回答
0

如果您想在其他方法中使用实例化的文本框,那么您可以通过将它们传递给方法或将它们存储为类的成员来实现。

将它们存储在下面的类中的示例。

public class YourForm
{
    private TextBox txtRun;
    private TextBox txtRun2;

    private void helloButton_Click(object sender, EventArgs e)
    {
        txtRun = new TextBox();
        txtRun2 = new TextBox();

        // removed less interesting initialization for readability

        this.Controls.Add(txtRun);
        this.Controls.Add(txtRun2);
    }

    public void DoStuffWithTextBoxes()
    {
        if (txtRun != null && txtRun2 != null)
        {
            // Retrieve text value and pass the values to another method
            SomeOtherMagicMethod(txtRun.Text, txtRun2.Text);
        }
    }

    private void SomeOtherMagicMethod(string txtRunText, string txtRun2Text)
    {
        // Do more magic
    }
}
于 2013-02-09T10:14:56.843 回答