Reputation: 34109
I have field's data type defined in database. I want to convert field's value to its specific data type.
The code below works for System.Int32
var fieldValue = "1234";
var fieldDataType = "System.Int32";
var type = Type.GetType(fieldDataType);
TypeConverter typeConverter = TypeDescriptor.GetConverter(type);
var result = typeConverter.ConvertFromString(fieldValue);
However, It does not work when dataType is System.Nullable<System.Int32>
What is the valid value for Nullable Integer DataType? (I am going to use the same for other datatypes)
EDIT 1 ( More details)
In database i have fields defined along with their data types. I am rendering TextBox
dynamically on UI for each field. When user submits the form
, I am using custom model binding in ASP.NET Core
to bind these fields to JObject.
Something like below
var model = new MyModel()
{
CustomFields = new JObject()
};
foreach(var key in form.Keys)
{
var val = form[key];
var fields = GetFieldsFromDB();
var field = fileds.Where(x=>x.FieldName == key).Single();
TypeConverter typeConverter = TypeDescriptor.GetConverter(Type.GetType(field.DataType);
var result = typeConverter.ConvertFromString(fieldValue);
model.CustomFields.Add(key,result);
}
I am trying to avoid switch
statement or if else
for each available .Net DataTypes
Upvotes: 0
Views: 217
Reputation: 15203
You need to use the internal type name:
var fieldDataType = "System.Nullable`1[System.Int32]";
This is also what's computed by:
var fieldDataType = "" + typeof(Nullable<int>);
Upvotes: 1