C# DataTable用法
//建立一个表
DataTable tDataTable = new DataTable("test");
//建立一个列
DataColumn tDataCol = new DataColumn("name", System.Type.GetType("System.String"));
//添加列
tDataTable.Columns.Add(tDataCol);
tDataCol = new DataColumn("age", System.Type.GetType("System.Int32"));
//添加列
tDataTable.Columns.Add(tDataCol);
//添加每行数据
DataRow tDataRow = tDataTable.NewRow();
tDataRow["name"] = "xiaoming";
tDataRow["age"] = 14;
tDataTable.Rows.Add(tDataRow);
DataRow tDataRowOne = tDataTable.NewRow();
tDataRowOne["name"] = "xiaoqiang";
tDataRowOne["age"] = 24;
tDataTable.Rows.Add(tDataRowOne);
//遍历Datatable
foreach (DataRow t in tDataTable.Rows)
{
object Name = t[0];
object age = t[1];
}
//删除数据
DataRow[] tDelet = tDataTable.Select("name = 'xiaoming'");
tDataTable.Rows.Remove(tDelet[0]);
public DataTable GetAllDataTable(DataSet ds)
{
DataTable newDataTable = ds.Tables[0].Clone(); //创建新表 克隆以有表的架构。
object[] objArray = new object[newDataTable.Columns.Count]; //定义与表列数相同的对象数组 存放表的一行的值。
for (int i = 0; i < ds.Tables.Count; i++)
{
for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
{
ds.Tables[i].Rows[j].ItemArray.CopyTo(objArray, 0); //将表的一行的值存放数组中。
newDataTable.Rows.Add(objArray); //将数组的值添加到新表中。
}
}
return newDataTable; //返回新表。
}
//------------------------------------------------------------------------------------------------------------------------------
将两个DataTable合并成一个DataTable //两个结构一样的DT合并
DataTable DataTable1 = new DataTable();
DataTable DataTable2 = new DataTable();
DataTable newDataTable = DataTable1.Clone();
object[] obj = new object[newDataTable.Columns.Count];
for (int i = 0; i < DataTable1.Rows.Count; i++)
{
DataTable1.Rows[i].ItemArray.CopyTo(obj,0);
newDataTable.Rows.Add(obj);
}
for (int i = 0; i < DataTable2.Rows.Count; i++)
{
DataTable2.Rows[i].ItemArray.CopyTo(obj,0);
newDataTable.Rows.Add(obj);
}
//两个结构不同的DT合并
/// <summary>
/// 将两个列不同的DataTable合并成一个新的DataTable
/// </summary>
/// <param name="dt1">表1</param>
/// <param name="dt2">表2</param>
/// <param name="DTName">合并后新的表名</param>
/// <returns></returns>
private DataTable UniteDataTable(DataTable dt1, DataTable dt2, string DTName)
{
DataTable dt3 = dt1.Clone();
for (int i = 0; i < dt2.Columns.Count; i++)
{
dt3.Columns.Add(dt2.Columns[i].ColumnName);
}
object[] obj = new object[dt3.Columns.Count];
for (int i = 0; i < dt1.Rows.Count; i++)
{
dt1.Rows[i].ItemArray.CopyTo(obj, 0);
dt3.Rows.Add(obj);
}
if (dt1.Rows.Count >= dt2.Rows.Count)
{
for (int i = 0; i < dt2.Rows.Count; i++)
{
for (int j = 0; j < dt2.Columns.Count; j++)
{
dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString();
}
}
}
else
{
DataRow dr3;
for (int i = 0; i < dt2.Rows.Count - dt1.Rows.Count; i++)
{
dr3 = dt3.NewRow();
dt3.Rows.Add(dr3);
}
for (int i = 0; i < dt2.Rows.Count; i++)
{
for (int j = 0; j < dt2.Columns.Count; j++)
{
dt3.Rows[i][j + dt1.Columns.Count] = dt2.Rows[i][j].ToString();
}
}
}
dt3.TableName = DTName; //设置DT的名字
return dt3;
}