【问题标题】:Validate input to a simple textbox depending on chosen type根据所选类型验证对简单文本框的输入
【发布时间】:2017-11-13 22:25:19
【问题描述】:

我正在为我的新一年做一些准备,但我有点让自己陷入了无法解决的混乱之中。如果你看下图:

你可以看到我有一个文本框,我不知道如何让它只接受某些字符,例如 0-7 sans 8 和 9 用于八进制。

到目前为止,这是我的代码:

private void inputBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (hexRadioButton.Checked)
        {
            if (char.IsWhiteSpace(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        if (decimalRadioButton.Checked)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) ||  char.IsWhiteSpace(e.KeyChar))
            {                    
                e.Handled = true;
            }
        }

        if (octalRadioButton.Checked)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) ||  char.IsWhiteSpace(e.KeyChar))
            { 
                e.Handled = true;
            }
            e.Handled = false;
        }

        if (radioButton1.Checked)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) || char.IsWhiteSpace(e.KeyChar))
            {
                e.Handled = true;
            }
            e.Handled = false;
        }
    }

我也尝试过这样做:

if (octalRadioButton.Checked)
            {
                if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) ||  char.IsWhiteSpace(e.KeyChar) || char.IsDigit('7') || char.IsDigit('8'))

但这几乎没有任何作用。

【问题讨论】:

  • 您应该能够通过查找单个类型(十进制、十六进制等)的验证来组合解决方案——您很可能会找到使用正则表达式来验证输入的解决方案。验证每一个 KeyPress 字符似乎非常混乱。花时间搜索每种类型的现有解决方案并相应地应用它们。

标签: c# dynamic textbox


【解决方案1】:

我认为最大的问题在这里:

if (octalRadioButton.Checked)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) ||  char.IsWhiteSpace(e.KeyChar))
    { 
        e.Handled = true;
    }
    e.Handled = false; <----------
}

将其设置为true 后,再次将其设置为false...这就是它允许您输入无效字符的原因。

所以删除那行。

第二个问题是你接受所有数字,包括 8 和 9。要解决这个问题,我会这样做:

var validChars = new[] {'1', '2', '3', '4', '5', '6', '7'};
if (!validChars.Contains(e.KeyChar)) {
    e.Handled = true;
}

您也可以将此方法用于其他基础。

编辑:

实际上,我只是查看了文档,Handled 显然不起作用。您需要 SuppressKeyPress 属性,并在 KeyDown 事件中将其设置为 true。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多