Add an object to a field of a DataTable c #

0

I have the following datatable with a DataRow

DataTable InfoHDVIndicador = new DataTable();
DataRow vlrInd = InfoHDVIndicador.NewRow();

with 18 columns, one of them is:

 /*18*/ InfoHDVIndicador.Columns.Add("FuentesArray");

It worked for me to create a Strings datatable without problem, however I want to send an object in # 18:

List<fuentesIndicador> fuente = new List<fuentesIndicador>();            

  fuentesIndicador fuentetemp = new fuentesIndicador() {
                        numeroCedula = result.Tables[0].Rows[i][0].ToString(),
                        nombre       = result.Tables[0].Rows[i][1].ToString(),
                        operacion    = result.Tables[0].Rows[i][4].ToString(),
                        campanas     = result.Tables[0].Rows[i][8].ToString(),
                    };

 fuente.Add(fuentetemp);

I add it to the dataRow

      vlrInd["FuentesArray"] = fuente;

and finally, I add this dataRow to the datatable:

 InfoHDVIndicador.Rows.Add(vlrInd);

However, he sends it to me as a String that is worth the following:

"System.Collections.Generic.List'1[LogicBo.HojaVidaIndicadoresBo.HojaVidaIndicadoresBo+fuentesIndicador]"

I need to send the object to retrieve it later, how should I send it or attach it to the datatable? Thanks.

    
asked by Andress Blend 05.12.2018 в 16:47
source

1 answer

2

A column of the datatable does not know it's an object the way you're assigning it, it only recognizes simple types like string , int , etc

If you want to assign an object you should serialize to xml or json

List<fuentesIndicador> fuente = new List<fuentesIndicador>();            

fuentesIndicador fuentetemp = new fuentesIndicador() {
                    numeroCedula = result.Tables[0].Rows[i][0].ToString(),
                    nombre       = result.Tables[0].Rows[i][1].ToString(),
                    operacion    = result.Tables[0].Rows[i][4].ToString(),
                    campanas     = result.Tables[0].Rows[i][8].ToString(),
                };

fuente.Add(fuentetemp);


XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<fuentesIndicador>));  

string result = "";
using(StringWriter textWriter = new StringWriter())
{
    xmlSerializer.Serialize(textWriter, fuente);
    result = textWriter.ToString();
}

vlrInd["FuentesArray"] = result;

As you will see the list is serialized to xml and then that string you assign to the row, to recover the data you only need to deserialize

Examples of XML Serialization

    
answered by 05.12.2018 / 17:03
source