如何使用 C# 在 Windows 表单中按下 Enter 键时从动态文本框提交和检索文本?

How to submit and retrieve text from dynamic textbox when Enter key is pressed in Windows forms using C#?

我有一个按钮,按下它会生成一个文本框。用户在文本框上写了一些东西,当按下回车键时,文本必须通过标签显示在相同的位置。

我已经能够创建动态文本框,我想我知道如何将文本分配给标签并在我获得文本后显示它。

互联网上的大多数教程都在谈论使用提交按钮并创建一个 AcceptButton 作为默认按钮,然后将它们链接起来。但是在这里我本身没有提交按钮。而且我一直无法弄清楚如何编写按键事件处理程序以及在何处编写它,因为文本框已经在事件处理程序中。

请帮忙

这是我能想到的。

int CMonSub;
private void btnMonSub_Click(object sender, EventArgs e)
{
    TextBox txtMonSub = new TextBox();
    txtMonSub.Name = "MonSub" + CMonSub;
    txtMonSub.Location = new System.Drawing.Point(155 + (100 * CMonSub), 60);
    CMonSub++;
    txtMonSub.Size = new System.Drawing.Size(100, 25);
    this.Controls.Add(txtMonSub);
    string s = txtMonSub.Text;
    Label l = new Label();
    l.Text = s;
    l.Location = new System.Drawing.Point(155 + (100 * CMonTime), 60);
    l.Size = new System.Drawing.Size(100, 25);
    this.Controls.Add(l);
}

我只需要在用户按下 Enter 键时获取该字符串。

也许我将文本分配给标签的部分也不是正确的方法。也非常感谢您提供帮助。

提前致谢。

如果您有多个文本框和标签,您将需要跟踪成对的文本框和标签,以便了解您正在处理的是哪一个。词典是最简单的方法。

您可以使用 KeyPress 事件查看用户何时单击某个键,并在输入该键时执行某些操作。

下面是一些示例代码:

    Dictionary<TextBox, Label> textBoxLabelPairing = new Dictionary<TextBox, Label>();

    private void btnMonSub_Click(object sender, EventArgs e)
    {
        TextBox txtMonSub = new TextBox();
        txtMonSub.Name = "MonSub" + CMonSub;
        txtMonSub.Location = new System.Drawing.Point(155 + (100 * CMonSub), 60);
        CMonSub++;
        txtMonSub.Size = new System.Drawing.Size(100, 25);

        //ADDED: keypress event
        txtMonSub.KeyPress += txtMonSub_KeyPress;

        this.Controls.Add(txtMonSub);
        string s = txtMonSub.Text;
        Label l = new Label();
        l.Text = s;
        l.Location = new System.Drawing.Point(155 + (100), 60);
        l.Size = new System.Drawing.Size(100, 25);
        this.Controls.Add(l);

        //ADDED: Dictionary Pairing
        textBoxLabelPairing.Add(txtMonSub, l);
    }

    void txtMonSub_KeyPress(object sender, KeyPressEventArgs e)
    {
        //if enter key is pressed
        if (e.KeyChar == (char)13)
        {
            TextBox thisTextBox = (TextBox)sender;
            Label associatedLabel = textBoxLabelPairing[thisTextBox];
            associatedLabel.Text = thisTextBox.Text;
        }
    }

此代码将为您创建的每个新文本框创建一个事件。唯一的问题是它总是触发相同的方法 (txtMonSub_KeyPress)。为了解决这个问题,您需要使用事件中的发件人(如代码中所示),以便您知道刚刚更新了哪个文本框。从那里,您可以使用您的字典对象来查看需要更新的标签(因为我们在前面的方法中将它们配对)。

更新:

如果你真的想要处理文本框,你可以这样做:

    void txtMonSub_KeyPress(object sender, KeyPressEventArgs e)
    {
        //if enter key is pressed
        if (e.KeyChar == (char)13)
        {
            TextBox thisTextBox = (TextBox)sender;
            string textBoxText = thisTextBox.Text;
            Label associatedLabel = textBoxLabelPairing[thisTextBox];
            associatedLabel.Text = textBoxText;
            this.Controls.Remove(thisTextBox);
            thisTextBox.Dispose();
        }
    }