c# - .Focus() 在 TextChangedEvent 中不起作用
问题描述
我已经在我的 Windows 窗体 C# 程序中实现了一些代码,问题是我想使用以下代码TextChangeEvent
而不是Validating
事件,但是.Focus()
and.Select()
方法不起作用。
解决方案是什么?
private void jTextBox5_TextChangeEvent(object sender, EventArgs e)
{
if (jTextBox5.TextValue != "John")
{
jTextBox5.Focus();
}
}
解决方案
如果您试图强制用户只能在文本框中键入单词“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;
}
推荐阅读
- python - Flask WTForms 用变量自动填充 StringField
- reactjs - 将 webpack-stream 与 gulp 一起使用时的奇怪行为
- powershell - 使用 powershell 获取对 Active Directory 分发列表的最新更改
- sas - sas ods --> ppt 总是'修复消息'
- c# - 无法将类型“void”隐式转换为“string”
- puppet - 为什么puppet中的exec资源的previous_value总是notrun?
- gradle - Gradle:shadowJar 将依赖项排除在外
- c++ - 条件变量中的 gcc 错误::wait_for
- mysql - 试图将西里尔符号插入 mysql 表
- vue.js - 使用动态 vue 输入的新值