我正在 Visual Studio 12 中创建一个 Windows 商店应用程序,我正在使用 c# 语言,我有一个文本框,但是如何使它只接受数字,如果用户尝试输入除数字之外的任何其他值,它应该显示错误信息
问问题
13904 次
3 回答
2
除了其他答案之外,当您正在编写 Windows 应用商店应用程序并且很可能会处理虚拟键盘时,您可以通过正确设置InputScope
of来确保获得合适的键盘视图(此处为 MSDN 链接)TextBox
<TextBox InputScope="Number" .../>
这里描述了一堆有用的InputScope
值。
请注意,您仍然需要按照其他答案中的说明进行验证,因为您必须满足用户覆盖显示的键盘类型或连接物理键盘的需求。我会用KeyDown
事件处理程序来做,就像这样
private void TextBox_KeyDown_Number(object sender, KeyRoutedEventArgs e)
{
if ((uint)e.Key >= (uint)Windows.System.VirtualKey.Number0
&& (uint)e.Key <= (uint)Windows.System.VirtualKey.Number9)
{
e.Handled = false;
}
else e.Handled = true;
}
于 2013-05-02T06:20:42.900 回答
0
你可以使用try and catch
或者您可以通过执行此操作获取更多代码来确定输入是否为数字(int 或 double)
//---------------------------------------------------------------------------
bool TFmBatteryConfiguration::IsValidInt(char* x)
{
bool Checked = true;
int i = 0;
do
{
//valid digit?
if (isdigit(x[i]))
{
//to the next character
i++;
Checked = true;
}
else
{
//to the next character
i++;
Checked = false;
break;
}
} while (x[i] != '\0');
return Checked;
}
//---------------------------------------------------------------------------
bool TFmBatteryConfiguration::IsValidDouble(char* x)
{
bool Checked = true;
int i = 0;
do
{
//valid digit?
if (isdigit(x[i]))
{
//to the next character
i++;
Checked = true;
}
else if (x[i] == '.')
{
//First character
if (x[0] == '.')
{
Checked = false;
break;
}
else if (x[i] == '.' && x[i+1] == '\0')
{
Checked = false;
break;
}
else
{
//to the next character
i++;
}
}
else
{
i++;
Checked = false;
break;
}
} while (x[i] != '\0');
return Checked;
}
上面的代码直接取自我的 C++ 项目之一。但想法是一样的。C# 提供了char.isDigit()
于 2013-05-02T02:43:36.077 回答
0
您可以在以下示例中简单地使用try
和喜欢:catch
private void textBox1_TextChanged(object sender, EventArgs e)
{
int num;
try
{
num = int.Parse(textBox1.Text); //here's your value
label1.Text = num.ToString();
}
catch (Exception exc)
{
label2.Text = exc.Message;
}
}
于 2013-05-02T02:30:41.650 回答