How to Check an Integer using TryParse in C#?

Here I will explain how to check whether a string is containing only with integer type or not. In many cases we need to determine whether an user inputted text in TextBox or something else is integer or not. With the TryParse method we can easily determine it.

not throw an exception if the conversion fails. It Converts the string
representation of a number to its integer equivalent. A return value indicates whether the conversion succeeded.

These below controls are taken in the WebForm:
1. TextBox InputTxtBx
2. Button SubmitBtn
3. Label ResultLabel
And we have to check whether the user inputted text of the InputTxtBx is integer
or not using TryParse method.

Here is the C# Code:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)

protected void SubmitButton_Click(object sender, EventArgs e)
string input = InputTxtBx.Text;
int check=0;
Boolean valid = int.TryParse(input, out check);
if (valid == true)
ResultLabel.Text = "You have Submitted: " + input;
InputTxtBx.Text = null;
ResultLabel.Text = "Input Integer Only";


No responses found. Be the first to comment...

  • Name: