My Simple World

access new world!

c#修改有数据Datatable列类型的方法

8 months ago · 1 MIN READ
#Working  #Learning 

c#修改有数据Datatable列类型的方法,三种方式,别人总结的特别好,特地备注一下。

Changing data type of datatable after get filled is not possible but one of the work abound for this is clone datatable and change type

First way

//clone datatable     
DataTable dtCloned = dt.Clone();
//change data type of column
dtCloned.Columns[0].DataType = typeof(Int32);
//import row to cloned datatable
foreach (DataRow row in dt.Rows) 
{
    dtCloned.ImportRow(row);
}

second way

and other way to do it is like this , fill schema first - than change column datatype and than fill datable

adapter.FillSchema(table, SchemaType.Source);
table.Columns[0].DataType = typeof (Int32);
adapter.Fill(table);

third way

one more way to do it is

System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Col1", typeof(int));
dt.Rows.Add(1);

System.Data.DataTable dt2 = new System.Data.DataTable();
dt2.Columns.Add("Col1", typeof(string));
dt2.Load(dt.CreateDataReader(), System.Data.LoadOption.OverwriteChanges);

原始地址

···

neo wing



Proudly powered by Canvas · Sign In