我创建了基于表单的程序需要一定的输入验证。 我需要确保用户只能在距离文本框内输入数值。
到目前为止,我已经签了文本框在它的东西,但是如果它有一个值,那么就应该进行,以验证所输入的值是数字:
else if (txtEvDistance.Text.Length == 0)
{
MessageBox.Show("Please enter the distance");
}
else if (cboAddEvent.Text //is numeric)
{
MessageBox.Show("Please enter a valid numeric distance");
}
Answer 1:
您可以尝试的TryParse方法,它允许你将一个字符串解析为一个整数,并返回一个布尔结果表明操作的成功或失败。
int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
// it's a valid integer => you could use the distance variable here
}
Answer 2:
如果你想防止输入非数值的用户在文本框中输入信息时,您可以使用的OnKeyPress事件是这样的:
private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true; //Just Digits
if (e.KeyChar == (char)8) e.Handled = false; //Allow Backspace
if (e.KeyChar == (char)13) btnSearch_Click(sender, e); //Allow Enter
}
如果用户粘贴使用鼠标的文本框的信息,此解决方案不起作用在这种情况下(右键点击/粘贴),你应该添加一个额外的验证。
Answer 3:
这里是另一个简单的解决方案
try
{
int temp=Convert.ToInt32(txtEvDistance.Text);
}
catch(Exception h)
{
MessageBox.Show("Please provide number only");
}
Answer 4:
您可以通过JavaScript的在客户端或使用文本框的一些正则表达式验证做到这一点。
使用Javascript
script type="text/javascript" language="javascript">
function validateNumbersOnly(e) {
var unicode = e.charCode ? e.charCode : e.keyCode;
if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
return true;
}
else {
window.alert("This field accepts only Numbers");
return false;
}
}
</script>
文本框(与固定ValidationExpression)
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator>
Answer 5:
你可以做这样
int outParse;
// Check if the point entered is numeric or not
if (Int32.TryParse(txtEvDistance.Text, out outParse) && outParse)
{
// Do what you want to do if numeric
}
else
{
// Do what you want to do if not numeric
}
Answer 6:
我同意Int.TryParse但作为替代,你可以使用正则表达式。
Regex nonNumericRegex = new Regex(@"\D");
if (nonNumericRegex.IsMatch(txtEvDistance.Text))
{
//Contains non numeric characters.
return false;
}
Answer 7:
我有这个扩展这是一种多用途:
public static bool IsNumeric(this object value)
{
if (value == null || value is DateTime)
{
return false;
}
if (value is Int16 || value is Int32 || value is Int64 || value is Decimal || value is Single || value is Double || value is Boolean)
{
return true;
}
try
{
if (value is string)
Double.Parse(value as string);
else
Double.Parse(value.ToString());
return true;
}
catch { }
return false;
}
它适用于其他数据类型。 应罚款为你想要做什么。
Answer 8:
if (int.TryParse(txtDepartmentNo.Text, out checkNumber) == false)
{
lblMessage.Text = string.Empty;
lblMessage.Visible = true;
lblMessage.ForeColor = Color.Maroon;
lblMessage.Text = "You have not entered a number";
return;
}
Answer 9:
这里有一个解决方案,允许使用数字只能用减号或十进制用减号和小数点。 大部分以前的答案并没有考虑到选定的文本。 如果您改变文本框的ShortcutsEnabled为false,那么你就不能垃圾粘贴到您的文本框或者(它禁用右键单击)。 一些解决方案,允许您在减去之前输入的数据。 请确认我抓到的一切!
private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
{
if (numeric)
{
// Test first character - either text is blank or the selection starts at first character.
if (txt.Text == "" || txt.SelectionStart == 0)
{
// If the first character is a minus or digit, AND
// if the text does not contain a minus OR the selected text DOES contain a minus.
if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
return false;
else
return true;
}
else
{
// If it's not the first character, then it must be a digit or backspace
if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back))
return false;
else
return true;
}
}
else
{
// Test first character - either text is blank or the selection starts at first character.
if (txt.Text == "" || txt.SelectionStart == 0)
{
// If the first character is a minus or digit, AND
// if the text does not contain a minus OR the selected text DOES contain a minus.
if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
return false;
else
{
// If the first character is a decimal point or digit, AND
// if the text does not contain a decimal point OR the selected text DOES contain a decimal point.
if ((e.KeyChar == '.' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains(".") || txt.SelectedText.Contains(".")))
return false;
else
return true;
}
}
else
{
// If it's not the first character, then it must be a digit or backspace OR
// a decimal point AND
// if the text does not contain a decimal point or the selected text does contain a decimal point.
if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back) || (e.KeyChar == '.' && (!txt.Text.Contains(".") || txt.SelectedText.Contains("."))))
return false;
else
return true;
}
}
}
Answer 10:
要检查是否值是双:
private void button1_Click(object sender, EventArgs e)
{
if (!double.TryParse(textBox1.Text, out double myX))
{
System.Console.WriteLine("it's not a double ");
return;
}
else
System.Console.WriteLine("it's a double ");
}
文章来源: Validating a Textbox field for only numeric input.