Converting values in an object to a type of an entity field

Posts   
 
    
9ppel
User
Posts: 17
Joined: 26-Feb-2007
# Posted on: 22-Jun-2007 22:09:14   

This is more like a general C#-question than a LLBLGEN-question maybe, but I'll try it here, in case someone has done the same thing while using LLBLGEN-classes.

I have an entity-class named Regd0230Entity:

Regd0230Entity regd0230 = new Regd0230Entity();

I'm going to read values from columns in an Excel-sheet and put those values into fields of the regd0230Entity. Which columns and which fields are up to the user to choose. So, one time the value in column A should be the value of the decimal-field regd0230.Price, the next time it could be the value of the string-field regd0230.Name etc.

So, I want to read alle the values from the Excels-sheet into a DataTable-object. I'll then have to set the name and type of each column:

string columnName = "Price"; . . . myDataTable.Columns.Add("Price", regd0230.Fields[columnName].DataType);

So far so good. Then I'll have to read the values into the regd0230Entity-object. That's where the problem is. I don't know which fields are going to be used from time to time, so I don't know the type of the fields. I can get the type by using

regd0230.Fields[columnName].DataType

, but I can't use something like

regd0230.SetNewFieldValue(columnName, (regd0230.Fields[columnName].DataType).TryParse(valueReadFromExcel));

Like, if (regd0230.Fields[columnName].DataType) is an decimal, and I knew this at runtime, I could use "decimal.TryParse(valueReadFromExcel)", but since I don't know this, I can't hardcode the datatype, and I don't know how to solve this without using a major switch-statement, which is not that elegant.

Not very elegant explanation, I know, but do anyone understand the problem and have a solution to it?

9ppel
User
Posts: 17
Joined: 26-Feb-2007
# Posted on: 23-Jun-2007 00:34:59   

OK, to answer my own question:

Looks like this may work:

string fieldName = "Price";

regd0230.SetNewFieldValue(fieldName, Convert.ChangeType(valueFromExcel, (regd0230.Fields[fieldName].DataType)));