Casting an unknown guy and putting him in a datarow column

1

I have a DataTable that has been created with the same columns as another DataTable.

DataTable dtAux = new DataTable();
for (int i = 0; i < dt.Columns.Count; i++)
{
      dtAux.Columns.Add(dt.Columns[i].ToString(), dt.Columns[i].GetType());
}

Later I want to add records to the dtAux dataTable, depending on whether they meet certain requirements

for (int i = 0; i < dgvAux.Rows.Count; i++)
{
      foreach (DataRow dr in dt.Rows)
      {
          if ((dr[0].ToString() == dgvAux.Rows[i].Cells[0].Value.ToString()))
          {
               DataRow drAux = dtAux.NewRow();
               drAux[0] =  ((drAux[0].GetType()) (dr[0].ToString()));
               ...
               ...
               ...  
               dtAux.Rows.Add(drAux);
          }
       }
}

The problem arises when I try to put in dr[0] the value, previously cast, I can not get it right

    
asked by U. Busto 27.04.2017 в 11:58
source

2 answers

3

To copy a DataRow to another, as long as both have the same structure, you can simply copy the ItemArray property from one to another, so your code would look like this:

if ((dr[0].ToString() == dt.Rows[0][0].ToString())) 
{ 
     DataRow drAux = dtAux.NewRow(); 
     drAux.ItemArray = dr.ItemArray; 
     dtAux.Rows.Add(drAux); 
} 
    
answered by 27.04.2017 / 13:08
source
0

Without giving many explanations it is complicated but,

drAux[0] =  ((drAux[0].GetType()) (dr[0].ToString()));

I see that you try to cast dr[0].ToString() to the type of drAux[o] , but when doing ToString() the type will always be string.

So it will give you a bug if the type of drAux[0] is not string too.

    
answered by 27.04.2017 в 12:19