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);
