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 dataTable dtAux, 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't get it to do it right
To copy one
DataRow
to another, as long as they both have the same structure, you can simply copy the propertyItemArray
from one to the other, so your code would look like this:Without giving many explanations it is complicated but,
I see that you try to cast
dr[0].ToString()
the type ofdrAux[o]
, but when doingToString()
the type it will always be string.Therefore, it will give you an error if the type of
drAux[0]
is not string as well.