Foreach of an object c #

3

Good afternoon, what I'm 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]));
                    }
                }


            }

        }

    
asked by Ariel Octavio D'Alfeo 20.02.2016 в 00:58
source

2 answers

3

If we analyze the property

PropertyInfo.SetValue (Method)

You'll see that it has two parameters, so it should be

propertyInfo.SetValue(campo, Convert.ToString(dt.Rows[j][i]));
    
answered by 20.02.2016 / 01:04
source
0

For each row it is necessary to create an instance of the class Field 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.

propertyInfo.SetValue(campo, dt.Rows[j][i], null);

If you also want to convert to the property type you can do the following

propertyInfo.SetValue(campo, Convert.ChangeType(dt.Rows[j][i], propertyInfo.PropertyType), null);
    
answered by 20.02.2016 в 01:18