原文:DataTable 更改在有数据列的类型方法
/// <summary>
/// 修改数据表DataTable某一列的类型和记录值(正确步骤:1.克隆表结构,2.修改列类型,3.修改记录值,4.返回希望的结果)
/// </summary>
/// <param name="argDataTable">数据表DataTable</param>
/// <returns>数据表DataTable</returns>
private DataTable UpdateDataTable(DataTable argDataTable)
{
DataTable dtResult = new DataTable();
//克隆表结构
dtResult = argDataTable.Clone();
foreach (DataColumn col in dtResult.Columns)
{
if (col.ColumnName == "testColumn")
{
//修改列类型
col.DataType = typeof(DateTime);
}
}
foreach (DataRow row in argDataTable.Rows)
{
DataRow newDtRow = dtResult.NewRow();
foreach (DataColumn column in argDataTable.Columns)
{
if (column.ColumnName == "testColumn")
{
newDtRow[column.ColumnName] = Convert.ToDateTime(row[column.ColumnName]);
}
else
{
newDtRow[column.ColumnName] = row[column.ColumnName];
}
}
dtResult.Rows.Add(newDtRow);
}
return dtResult;
}