【问题标题】:.Focus() doesn't work in TextChangedEvent.Focus() 在 TextChangedEvent 中不起作用
【发布时间】:2019-06-17 18:27:48
【问题描述】:

我在我的 Windows 窗体 C# 程序中实现了一些代码,问题是我希望在 TextChangeEvent 中使用以下代码而不是 Validating 事件,但 .Focus().Select() 方法不不行。

解决办法是什么?

private void jTextBox5_TextChangeEvent(object sender, EventArgs e)
{
    if (jTextBox5.TextValue != "John")
    {
        jTextBox5.Focus();
    }
}

【问题讨论】:

  • 试试.Select()(见this question
  • @Joelius 我也试过了,还是不行
  • 请更详细地描述“[the] methods don't work”的意思,具体来说,您想在这里强制执行什么行为?通常,如果一个控件的Text 发生变化,那么它已经有Focus,所以在那个时候尝试给控件Focus 是没有意义的。
  • 还有,jTextBox5是个什么控件? winforms TextBox 控件没有TextValue 属性。
  • @RufusL 我希望能够只编辑该文本框,除非文本框中的文本是“john”,换句话说,.focus() 不能正常工作TextChangeEvent 它让我可以编辑其他文本框,而不管其中写入的 if 条件

标签: c# winforms focus textchanged


【解决方案1】:

你可以试试:

private void jTextBox5_TextChangeEvent(object sender, EventArgs e)
{
    if (jTextBox5.Text.ToUpper().Trim() != "JOHN")
    {
        ((Textbox)sender).Focus();
}

【讨论】:

  • 对不起,我帮不上忙。
【解决方案2】:

如果您试图强制用户只能在文本框中键入单词“John”,并且您希望在每次按键时验证这一点,那么您可以执行以下代码,它检查当前文本,一次一个字符,并将每个字符与单词“John”中的对应字符进行比较。

如果一个字符不匹配,那么我们将文本设置为仅匹配匹配的字符的子字符串,这样他们就可以继续输入:

private void jTextBox5_TextChanged(object sender, EventArgs e)
{
    var requiredText = "John";

    // Don't allow user to type (or paste) extra characters after correct word
    if (jTextBox5.Text.StartsWith(requiredText))
    {
        jTextBox5.Text = requiredText;
    }
    else
    {
        // Compare each character to our text, and trim the text to only the correct entries
        for (var i = 0; i < jTextBox5.TextLength; i++)
        {
            if (jTextBox5.Text[i] != requiredText[i])
            {
                jTextBox5.Text = jTextBox5.Text.Substring(0, i);
                break;
            }
        }
    }

    // Set the selection to the end of the text so they can keep typing
    jTextBox5.SelectionStart = jTextBox5.TextLength;
}

【讨论】:

    猜你喜欢
    • 2013-07-03
    • 2023-03-31
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    相关资源
    最近更新 更多