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);
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

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