【问题标题】:How do I enter the text in the specific textbox using button click如何使用按钮单击在特定文本框中输入文本
【发布时间】:2011-12-03 11:49:48
【问题描述】:

我正在开发一个 WinForms 应用程序。我的表单中有四个文本框和一个按钮。我在单击按钮时使用textBox1.SelectedText += "any string",因此它会写入第一个TextBox。如果我添加textBox1.SelectedText += "any string.",那么它会同时写入 textbox1 和 textbox 2。

当我点击 textbox1 并按下按钮时,刺痛只写在第一个文本框中,我点击第二个文本框并按下按钮然后它写入第二个文本框。有什么办法吗?

我正在使用以下代码。

private void button1_Click(object sender, EventArgs e)
{
    textBox1.SelectedText += "abc";
    textBox2.SelectedText += "abc";          
}

当我专注于控件时,当我们按下按钮时,焦点转到按钮上。那么如何在按下按钮后将焦点放在表单的其中一个文本框上呢?

【问题讨论】:

  • 我认为你的标题是错误的:“我如何输入文本...”,但是在你问的问题中“我们如何才能关注焦点按下按钮后在我表单的一个文本框上“...
  • 道歉..我写错了标题。这将是你写的。

标签: c# winforms


【解决方案1】:

你可以试试这个

    TextBox selTB = null;

    public Form1()
    {
        InitializeComponent();
        textBox1.Enter += tb_Enter;
        textBox2.Enter += tb_Enter;
        textBox3.Enter += tb_Enter;
        textBox4.Enter += tb_Enter;
    }

    ~Form1()
    {
        textBox1.Enter -= tb_Enter;
        textBox2.Enter -= tb_Enter;
        textBox3.Enter -= tb_Enter;
        textBox4.Enter -= tb_Enter;
    }

    private void tb_Enter(object sender, EventArgs e)
    {
        selTB = (TextBox)sender;
    }


    private void button1_Click(object sender, EventArgs e)
    {
        // Do what you need
        selTB.SelectedText += "abc";

        // Focus last selected textbox
        if (selTB != null) selTB.Focus();
    }

这个想法是当你输入一个文本框时,你将它存储在selTB
因此,当您单击按钮时,您就知道最后选择的是哪个文本框。

【讨论】:

  • 嗨,我的问题是,当我们单击 textbox1 并按下按钮时,与按钮相关联的文本仅转到 textbox1。如果我选择 textbox2 并按下按钮,那么它只会转到 textbox2 而不是两个文本框。我该怎么做?
  • @vipinkatiyar:我编辑了我的答案,将文本放入文本框中。这是你需要的吗?你试过我的代码吗?告诉我
  • 我实现了代码 Marco,但我的“selTB”始终为空。我不知道发生了什么
  • @MARKANDBhatt:在tb_Enter中放一个断点,检查它是否被调用;你确定你有文本框吗?
  • 我试过了。 tb_Enter 被调用。但是当涉及到按钮单击事件时,“selTb”为空。
【解决方案2】:

您可以按以下方式进行采样,希望这会给您带来灵感。

 public partial class Form7 : Form
 {
    private TextBox textBox = null;
    public Form7()
    {
        InitializeComponent();

        // Binding to custom event process function GetF.
        this.textBox1.GotFocus += new EventHandler(GetF);
        this.textBox2.GotFocus += new EventHandler(GetF);
    }

    private void GetF(object sender, EventArgs e)
    {
        // Keeps you selecting textbox object reference.
        textBox = sender as TextBox;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        // Changes you text box text.
        if (textbox != null) textBox.SelectedText += "You text";
    }
}

【讨论】:

  • @JKhuang, vipin:我修改了代码,如果在用户单击按钮之前没有选择 TextBox,您不会收到 NullReferenceException。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-03
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多