如何在使用TextChanged输入之前清除字段

本文关键字:清除 字段 输入 TextChanged | 更新日期: 2023-09-27 18:17:48

所以我要做的是能够连续输入所有10个文本框。我从第一个开始,然后在键入3个字符后将焦点更改为下一个,在键入3个字符后将焦点更改为下一个。

我已经完成了这部分,但是如果在第二个文本框中已经有文本怎么办?我有尝试Clear(),但它创建了一个错误,不会让我输入超过1个字符。

所以当所有的文本框都填满了垃圾数据,所以当我开始输入第一个文本框123然后移动到第二个文本框456第三789等。但是当下一个字段先被清除时

我正在努力解决这个问题:

    public PingIPRange()
    {
        InitializeComponent();
        txtF1.TextChanged += new EventHandler(NextField);
        txtF2.TextChanged += new EventHandler(NextField);
        txtF3.TextChanged += new EventHandler(NextField);
        txtF4.TextChanged += new EventHandler(NextField);
        txtT1.TextChanged += new EventHandler(NextField);
        txtT2.TextChanged += new EventHandler(NextField);
        txtT3.TextChanged += new EventHandler(NextField);
        txtT4.TextChanged += new EventHandler(NextField);
        txtInterval.TextChanged += new EventHandler(NextField);
        txtRepeat.TextChanged += new EventHandler(NextField);
    }
    private void NextField(object sender, EventArgs e)
    {
        if (txtF1.TextLength == 3)
        {
            txtF2.Focus();              
        }
        if (txtF2.TextLength == 3)
        {
            txtF3.Focus();
        }
        if (txtF3.TextLength == 3)
        {
            txtF4.Focus();
        }
        if (txtF4.TextLength == 3)
        {
            txtT1.Focus();
        }
        if (txtT1.TextLength == 3)
        {
            txtT2.Focus();
        }
        if (txtT2.TextLength == 3)
        {
            txtT3.Focus();
        }
        if (txtT3.TextLength == 3)
        {
            txtT4.Focus();
        }
        if (txtT4.TextLength == 3)
        {
            txtInterval.Focus();
        }
        if (txtInterval.TextLength == 3)
        {
            txtRepeat.Focus();
        }
        if (txtRepeat.TextLength == 3)
        {
            btnPing.Focus();
        }
    }
}

如何在使用TextChanged输入之前清除字段

为文本框添加Enter事件,并对文本执行SelectAll

txtF2.Enter += SelectTextOnEnter;
txtF3.Enter += SelectTextOnEnter;
// etc.

private void SelectTextOnEnter(object sender, EventArgs e) { 
  ((TextBox)sender).SelectAll();
}

同样,你的NextField方法并不完全像你想象的那样。确保你的控件的TabIndex值是在正确的顺序,然后尝试改变你的代码如下:

private void NextField(object sender, EventArgs e) {
  if (((TextBox)sender).Text.Length == 3)
    this.SelectNextControl((Control)sender, true, true, false, false);
}

它将根据表单的制表符顺序选择下一个控件

我认为在调用Focus方法之前将textbox Text属性设置为空字符串会做你想要的。

if (txtF1.TextLength == 3)
{
    txtF2.Text = String.Empty;
    txtF2.Focus();
}
.
.
.