1

让我用这个例子来解释一下,假设我们有一个带有以下掩码的 MaskedTexBox它是格式__-__-____中日期的掩码。mm-dd-yyyy

在第一个位置,只有有效的月份实体是 0 或 1。

这部分我开始工作了,所以当用户按 2 到 9 时,它会自动使 MaskedTextBox = 02-__-____or 03-__-____or 04-__-____...09-__-____等。

看到它是如何工作的,我尝试移动到下一个位置。如果第一个数字为 0,则第二个位置唯一有效的条目将是 1-9,如果第一个数字是 1,则为 0-2。

但是通过在第一个位置按下第一个数字,第二个位置被正确设置。但是,如果用户退格或单击第二个位置并按下让说 0,如果第一个位置已经包含 0,我想阻止用户按 0。因为目前它看起来像这样00-__-____,那是一个无效的月份.

在“日”位置(第 3 和第 4 位)中,应仅允许第 3 位输入 0、1、2、3。在第 4 位中,仅允许某些数字,具体取决于第 3 位已有的内容。

位置 4 的逻辑:

  • 如果 3rd 是 0 那么位置 4 只能允许 1-9

  • 如果 3rd 是 1 或 2 那么位置 4 只能允许 0-9

  • 如果 3rd 是 3 那么位置 4 只能允许 0-1

“年”的位置(5、6、7、8)也有自己的逻辑。但是为了防止这个问题变得复杂或令人困惑,除非有人要求,否则我将避免发布该逻辑。

所以基本上 MaskedTextBox 字符串中的每个位置都有自己需要遵循的逻辑。我已经尝试了下面的代码,但我无法阻止用户在所述位置输入无效数字。我开始怀疑这样的事情是否不可能,因为我发现阻止用户输入/键入不需要的字符的其他示例只有 1 个 IF/ELSE 子句和 1e.Handled = false和 1 e.Handled = true。而我的需要很多放在深层的 IF/ELSE 子句中。

这在 C# 中使用 KeyPress 事件是否可行?

到目前为止我尝试过的代码。请原谅我一直在尝试很多选择但没有运气。我还没有完成下面代码中的“年”逻辑,因为我想让月份和日期部分首先工作。

    private void mtbTest_KeyPress(object sender, KeyPressEventArgs e)
    {
        Char pressedKey = e.KeyChar;

        mtbTest.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;

        int[] formatLengths = { 0 };

        if (Char.IsNumber(pressedKey))
        {
            if (formatLengths.Contains(mtbTest.Text.Length) && Convert.ToInt32(Char.GetNumericValue(pressedKey)) > 1)
            {
                mtbTest.Text = String.Format("{0}0", mtbTest.Text);
            }

            if (mtbTest.Text.Length == 1)
            {
                if (Convert.ToInt32(mtbTest.Text.Substring(0, 1)) == 0)
                {
                    if (Convert.ToInt32(Char.GetNumericValue(pressedKey)) > 1)
                    {
                        e.Handled = false;
                    }
                }

                if (Convert.ToInt32(mtbTest.Text.Substring(0, 1)) == 1)
                {
                    if (Convert.ToInt32(Char.GetNumericValue(pressedKey)) < 2)
                    {
                        e.Handled = false;
                    }
                }
            }

            if (mtbTest.Text.Length == 2 && Convert.ToInt32(Char.GetNumericValue(pressedKey)) > 3)
            {
                mtbTest.Text = String.Format("{0}0", mtbTest.Text);
            }

            if (mtbTest.Text.Length == 3)
            {
                if (Convert.ToInt32(mtbTest.Text.Substring(2, 1)) == 0)
                {
                    if (Convert.ToInt32(Char.GetNumericValue(pressedKey)) > 0)
                    {
                        e.Handled = false;
                    }
                }
            }

            if (mtbTest.Text.Length == 4 && Convert.ToInt32(Char.GetNumericValue(pressedKey)) > 1)
            {
                e.Handled = false;
            }

            e.Handled = true;
        }
        else
        {
            e.Handled = true;
        }

        mtbTest.TextMaskFormat = MaskFormat.IncludePromptAndLiterals;
    }
4

0 回答 0