Verify Numeric Value

Convert string to value without erroring on fail

	//Try and convert without checking result
	int.TryParse(MyStringValue, out Value);		//Value will be set to 0 if conversion fails

	//Convert and get result if it worked or not
	if (int.TryParse(MyStringValue, out Value))	//Returns true if conversion sucessful
	{
		//Conversion was sucessful
	}

For larger values:

    UInt64 Value = 123;
    ValueIsNumeric = UInt64.TryParse(MyStringValue, out Value);		//Value will be set to 0 if conversion fails

Verifying a form TextBox value example


    //*****************************************************
    //*****************************************************
    //*********** VERIFY NUMBERIC TEXT BOX VALUE **********
    //*****************************************************
    //*****************************************************
    private void VerifyTextBoxNumericValue(ref TextBox TextBox1, int MinValue, int MaxValue, int DefaultValue)
    {
        try
        {
            int Value = 0;
            if (!(int.TryParse(TextBox1.Text, out Value)))
            {
                TextBox1.Text = Convert.ToString(DefaultValue);
            }

            if (Value < MinValue)
                TextBox1.Text = Convert.ToString(MinValue);
            if (Value > MaxValue)
                TextBox1.Text = Convert.ToString(MaxValue);
        }
        catch (Exception)
        {
        }
    }

    VerifyTextBoxNumericValue(ref MyTextBox, 0, 256, 256);

Verify a byte array contains only ASCII characters

Skips the first 5 bytes, tests the rest

						bool IsAscii = RxData.Skip(5).Take(Rs485FeedReceivedPacketLength).All(b => (b >= ' ' && b <= '~') || b == '\r' || b == '\n');	//Check the data is all ascii characters
						if (!IsAscii)
							break;
						sTemp = "";
						sTemp = System.Text.Encoding.UTF8.GetString(RxData, 5, Rs485FeedReceivedPacketLength);
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through resources like this. We hope you find it helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support here. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *