Auto conversion

Posts   
 
    
AlexWalker
User
Posts: 40
Joined: 05-Nov-2008
# Posted on: 06-Nov-2008 21:53:07   
_entity.SetNewFieldValue(_entityFieldName, _textBox.Text);

When trying the code below where textBox.Text is a System.String and the Entity field is a Nullable Decimal, I'm getting an ORMValueTypeMismatchException.

How can I get LLBL to try to convert the string to a decimal?

This bit of code is being called for lots of fields on a form, so casting to a decimal won't work, since the other TextBoxes aren't decimals.

In addition, it looks like the DataType doesn't indicate decimal, but rather Nullable, so I'm not sure I can do dynamic type casting.

MTrinder
User
Posts: 1461
Joined: 08-Oct-2008
# Posted on: 06-Nov-2008 22:12:46   

Not exactly elegant, but


_entity.Fields[_entityFieldName].DataType.FullName

will return something like


"System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"

You could parse the underlying datatype out of this and then do


switch parsedDataType
{
    case "DateTime":
    _entity.SetNewFieldValue(_entityFieldName, Convert.ToDateTime( _textBox.Text));
    break;

    case "Decimal":
    _entity.SetNewFieldValue(_entityFieldName, Convert.ToDecimal(_textBox.Text));
    break;

   etc...
    
}

If I can come up with anything more elegant I'll get back to you simple_smile

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39861
Joined: 17-Aug-2003
# Posted on: 07-Nov-2008 10:48:57   

Convert.ChangeType(_textBox.Text, _entity.Fields[_entityFieldName].DataType)

Might help. (Not tested)

Frans Bouma | Lead developer LLBLGen Pro
AlexWalker
User
Posts: 40
Joined: 05-Nov-2008
# Posted on: 07-Nov-2008 14:02:31   

Otis wrote:

Convert.ChangeType(_textBox.Text, _entity.Fields[_entityFieldName].DataType)

Might help. (Not tested)

Unfortunately, it doesn't, because the DataType is Nullable.

Here's an ugly bit of code that does the job.


Type dataType = _entity.Fields[_entityFieldName].DataType;
Type dataTypeToUse;
if (dataType.Name.Contains("Nullable"))
{
        string dataTypeName = dataType.FullName.Substring(dataType.FullName.IndexOf("[[") + "[[".Length, dataType.FullName.IndexOf(",") - dataType.FullName.IndexOf("[[") - "[[".Length);
        dataTypeToUse = Type.GetType(dataTypeName);
}
else
{
        dataTypeToUse = dataType;
}

 _entity.SetNewFieldValue(_entityFieldName, Convert.ChangeType(_textBox.Text, dataTypeToUse));

I understand that there may be reasons why LLBL wouldn't automatically try to convert a parameter before throwing an error, but it would be great if there was a version of SetNewFieldValue that would do just that.