Yes, you can.
I once came across your issue and implemented an extension for the Textbox control.
It's a generic method that can convert do Decimal, int, anything that is a value type.
public static T? GetTextOrNullStruct<T>(this TextBox txt, GlobalSist.Common.Utils.ParserCondition? parserCondition, bool throwOnValidation)
where T : struct, IComparable<T>
{
return GlobalSist.Common.Utils.Parsers.ConvertStruct<T>(
GetTextOrNull(txt), parserCondition, throwOnValidation);
}
public static T? ConvertStruct<T>(IConvertible value, ParserCondition? parserCondition, bool throwOnValidation)
where T : struct, IComparable<T>
{
try
{
if ((value == null) ||
(value is string && string.IsNullOrEmpty((string)value)))
{
if (throwOnValidation)
throw new ArgumentNullException("value");
else
return null;
}
return Parsers.Convert<T>(value, parserCondition, true);
}
catch (ArgumentOutOfRangeException)
{
if (throwOnValidation)
throw;
else
return null;
}
}
And here it is the method that converts to a string
public static T Convert<T>(IConvertible value, ParserCondition? parserCondition, bool throwOnValidation)
where T : IComparable<T>
{
T convertedValue;
try
{
convertedValue = (T)value.ToType(typeof(T), null);
}
catch (Exception ex)
{
if (throwOnValidation)
throw new ArgumentOutOfRangeException(ex.Message, ex);
else
return default(T);
}
return ValidateParserCondition<T>(convertedValue, parserCondition, throwOnValidation);
}
edit: Forgot to paste the last called method
private static T ValidateParserCondition<T>(T value, ParserCondition? parserCondition, bool throwOnValidation)
where T : IComparable<T>
{
if (parserCondition == null)
return value;
else
{
int comparingToZero = value.CompareTo(default(T));
switch (parserCondition.Value)
{
case ParserCondition.GreaterOrEqualToZero:
if (comparingToZero >= 0)
return value;
break;
case ParserCondition.GreaterThanZero:
if (comparingToZero > 0)
return value;
break;
case ParserCondition.LessOrEqualToZero:
if (comparingToZero <= 0)
return value;
break;
case ParserCondition.LessThanZero:
if (comparingToZero < 0)
return value;
break;
default:
throw new NotImplementedException("ParserCondition at ValidateParserCondition");
}
if (throwOnValidation)
throw new ArgumentOutOfRangeException(
string.Format("value {0} not in accordance with ParserCondition {1}",
value, parserCondition.Value.ToString()));
else
return default(T);
}
}
And the enum declaration is:
public enum ParserCondition
{
/// <summary>
/// >=0
/// </summary>
GreaterOrEqualToZero,
/// <summary>
/// >0
/// </summary>
GreaterThanZero,
/// <summary>
/// <=0
/// </summary>
LessOrEqualToZero,
/// <summary>
/// <0
/// </summary>
LessThanZero,
}
TryParse, thus assigning0Mfor invalid data; is that intentional?txtBasicSalary.