【发布时间】: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 字符似乎非常混乱。花时间搜索每种类型的现有解决方案并相应地应用它们。