如何防止按键更新 MaskedTextBox 的文本?

发布于 2024-07-15 04:35:51 字数 362 浏览 4 评论 0原文

我需要验证用户在 MaskedTextBox 中输入的字符。 哪些字符有效取决于已输入的字符。 我尝试过使用 IsInputCharOnKeyPress,但是我是否在 IsInputChar 中返回 false 或将 e.Handled 设置为在 OnKeyPress 中为 true 时,框的文本仍设置为无效值。

如何防止按键更新 MaskedTextBox 的文本?

更新:MaskedTextBox 不是 TextBox。 我认为这不会产生什么影响,但从告诉我 e.Handled 应该有效的人数来看,也许确实有效。

I need to validate characters entered by the user in a MaskedTextBox. Which characters are valid depends on those already entered. I've tried using IsInputChar and OnKeyPress, but whether I return false in IsInputChar or set e.Handled to true in OnKeyPress, the box's text is still set to the invalid value.

How do I prevent a keypress from updating a MaskedTextBox's text?

UPDATE: MaskedTextBox not TextBox. I don't think that should make a difference, but from the number of people telling me that e.Handled should work, perhaps it does.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

温暖的光 2024-07-22 04:35:51

这不会在 textbox1 中键入字符“x”。

    char mychar='x'; // your particular character
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == mychar)
            e.Handled = true;
    }

编辑:它也适用于 MaskedTextBox。

华泰

This will not type character 'x' in textbox1.

    char mychar='x'; // your particular character
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == mychar)
            e.Handled = true;
    }

EDIT: It works for MaskedTextBox as well.

HTH

_失温 2024-07-22 04:35:51

KeyPress 应该可以做到这一点; 你是在表格上做这个的吗? 或在控制? 例如:(

static void Main() {
    TextBox tb = new TextBox();
    tb.KeyPress += (s, a) =>
    {
        string txt = tb.Text;
        if (char.IsLetterOrDigit(a.KeyChar)
            && txt.Length > 0 &&
            a.KeyChar <= txt[txt.Length-1])
        {
            a.Handled = true;
        }
    };
    Form form = new Form();
    form.Controls.Add(tb);
    Application.Run(form);
}

仅允许“升序”字符)

请注意,这不会保护您免受复制/粘贴 - 您可能还需要查看 TextChanged 和/或 Validate。

The KeyPress should do it; are you doing this at the form? or at the control? For example:

static void Main() {
    TextBox tb = new TextBox();
    tb.KeyPress += (s, a) =>
    {
        string txt = tb.Text;
        if (char.IsLetterOrDigit(a.KeyChar)
            && txt.Length > 0 &&
            a.KeyChar <= txt[txt.Length-1])
        {
            a.Handled = true;
        }
    };
    Form form = new Form();
    form.Controls.Add(tb);
    Application.Run(form);
}

(only allows "ascending" characters)

Note that this won't protect you from copy/paste - you might have to look at TextChanged and/or Validate as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文