仅为数字输入验证文本框字段.

Wiz*_*ard 8 c# validation textbox

我创建了一个基于表单的程序,需要一些输入验证.我需要确保用户只能在距离文本框中输入数值.

到目前为止,我已经检查过Textbox中有一些内容,但是如果它有一个值,那么它应该继续验证输入的值是否为数字:

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");
        }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 17

您可以尝试使用TryParse方法,该方法允许您将字符串解析为整数并返回指示操作成功或失败的布尔结果.

int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
    // it's a valid integer => you could use the distance variable here
}
Run Code Online (Sandbox Code Playgroud)


Som*_*ody 6

如果要在TextBox中输入信息时阻止用户输入非数字值,可以使用Event 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            
        }
Run Code Online (Sandbox Code Playgroud)

如果用户使用鼠标(右键单击/粘贴)将信息粘贴到TextBox中,则此解决方案不起作用,在这种情况下,您应该添加额外的验证.


COL*_*OLD 5

这是另一个简单的解决方案

try
{
    int temp=Convert.ToInt32(txtEvDistance.Text);
}
catch(Exception h)
{
    MessageBox.Show("Please provide number only");
}
Run Code Online (Sandbox Code Playgroud)