Check whether String is int or float using C# and VB.Net in ASP.Net

Last Reply one year ago By pandeyism

Posted one year ago

Hello,

I want to check textbox text is float or integer from code behind in asp.net c#

how to do it please give reference

Posted one year ago

Hi ashishk,

Please refer below sample.

HTML

<div>
    <asp:TextBox ID="txtNumber" runat="server" />
    <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />
</div>

Code

C#

protected void btnSubmit_Click(object sender, EventArgs e)
{
    string number = txtNumber.Text;
    int intValue;
    float floatValue;
    if (int.TryParse(number, out intValue))
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Its a number')", true);
        return;
    }
    else if (float.TryParse(number, out floatValue))
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Its a float')", true);
        return;
    }
    else
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Its neither float nor number')", true);
    }
}

VB.Net

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim number As String = txtNumber.Text
    Dim intValue As Integer
    Dim floatValue As Single

    If Integer.TryParse(number, intValue) Then
        ClientScript.RegisterClientScriptBlock(Me.[GetType](), "", "alert('Its a number')", True)
        Return
    ElseIf Single.TryParse(number, floatValue) Then
        ClientScript.RegisterClientScriptBlock(Me.[GetType](), "", "alert('Its a float')", True)
        Return
    Else
        ClientScript.RegisterClientScriptBlock(Me.[GetType](), "", "alert('Its neither float nor number')", True)
    End If
End Sub

Screenshot