Good afternoon, what I am trying to do is set the attributes of a list of objects from a table with two for for the table and a foreach for the attributes of the object. I'm stuck on how to assign the value to the attribute.
/*recorre las filas*/
for (var j = 0; j < dt.Rows.Count; j++)
{
var campo = new Campo();
/*se para en cada fila y recorre las columnas*/
for (var i = 0; i < dt.Columns.Count; i++)
{
var nombreCampo = dt.Columns[i].Caption;
/*recorro las propiedades del objeto campo
* y cuando nombreCampo==propertyInfo.Name
* le asigno el valor de la celda segun cordenadas*/
foreach (PropertyInfo propertyInfo in campo.GetType().GetProperties())
{
if (propertyInfo.Name == nombreCampo)
{
propertyInfo.SetValue( Convert.ToString(dt.Rows[j][i]));
}
}
}
}
If we analyze the property
PropertyInfo.SetValue Method
You will see that this takes two parameters, so it should be
For each row it is necessary to create an instance of the Field class and save it in a list, otherwise you will always lose the object in each iteration.
That as a first point. Now, to set the value of the property you need to indicate which object in the first argument while the value in the second.
If you also want to do a conversion to the type of the property you can do the following