命名空间:

System.Data

程序集:

System.Data.Common.dll

参考连接:https://docs.microsoft.com/zh-cn/dotnet/api/system.data.datatable?view=netcore-3.1

下面示例显示如何创建两个DataTable,并将他们添加到DataSet中

using System;
using System.Data;
class Program
{
static void Main(string[] args)
{
// Create two tables and add them into the DataSet
DataTable orderTable = CreateOrderTable();
DataTable orderDetailTable = CreateOrderDetailTable();
DataSet salesSet = new DataSet();
salesSet.Tables.Add(orderTable);
salesSet.Tables.Add(orderDetailTable); // Set the relations between the tables and create the related constraint.
salesSet.Relations.Add("OrderOrderDetail", orderTable.Columns["OrderId"], orderDetailTable.Columns["OrderId"], true); Console.WriteLine("After creating the foreign key constriant, you will see the following error if inserting order detail with the wrong OrderId: ");
try
{
DataRow errorRow = orderDetailTable.NewRow();
errorRow[0] = 1;
errorRow[1] = "O0007";
orderDetailTable.Rows.Add(errorRow);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine(); // Insert the rows into the table
InsertOrders(orderTable);
InsertOrderDetails(orderDetailTable); Console.WriteLine("The initial Order table.");
ShowTable(orderTable); Console.WriteLine("The OrderDetail table.");
ShowTable(orderDetailTable); // Use the Aggregate-Sum on the child table column to get the result.
DataColumn colSub = new DataColumn("SubTotal", typeof(Decimal), "Sum(Child.LineTotal)");
orderTable.Columns.Add(colSub); // Compute the tax by referencing the SubTotal expression column.
DataColumn colTax = new DataColumn("Tax", typeof(Decimal), "SubTotal*0.1");
orderTable.Columns.Add(colTax); // If the OrderId is 'Total', compute the due on all orders; or compute the due on this order.
DataColumn colTotal = new DataColumn("TotalDue", typeof(Decimal), "IIF(OrderId='Total',Sum(SubTotal)+Sum(Tax),SubTotal+Tax)");
orderTable.Columns.Add(colTotal); DataRow row = orderTable.NewRow();
row["OrderId"] = "Total";
orderTable.Rows.Add(row); Console.WriteLine("The Order table with the expression columns.");
ShowTable(orderTable); Console.WriteLine("Press any key to exit.....");
Console.ReadKey();
} private static DataTable CreateOrderTable()
{
DataTable orderTable = new DataTable("Order"); // Define one column.
DataColumn colId = new DataColumn("OrderId", typeof(String));
orderTable.Columns.Add(colId); DataColumn colDate = new DataColumn("OrderDate", typeof(DateTime));
orderTable.Columns.Add(colDate); // Set the OrderId column as the primary key.
orderTable.PrimaryKey = new DataColumn[] { colId }; return orderTable;
} private static DataTable CreateOrderDetailTable()
{
DataTable orderDetailTable = new DataTable("OrderDetail"); // Define all the columns once.
DataColumn[] cols ={
new DataColumn("OrderDetailId",typeof(Int32)),
new DataColumn("OrderId",typeof(String)),
new DataColumn("Product",typeof(String)),
new DataColumn("UnitPrice",typeof(Decimal)),
new DataColumn("OrderQty",typeof(Int32)),
new DataColumn("LineTotal",typeof(Decimal),"UnitPrice*OrderQty")
}; orderDetailTable.Columns.AddRange(cols);
orderDetailTable.PrimaryKey = new DataColumn[] { orderDetailTable.Columns["OrderDetailId"] };
return orderDetailTable;
} private static void InsertOrders(DataTable orderTable)
{
// Add one row once.
DataRow row1 = orderTable.NewRow();
row1["OrderId"] = "O0001";
row1["OrderDate"] = new DateTime(2013, 3, 1);
orderTable.Rows.Add(row1); DataRow row2 = orderTable.NewRow();
row2["OrderId"] = "O0002";
row2["OrderDate"] = new DateTime(2013, 3, 12);
orderTable.Rows.Add(row2); DataRow row3 = orderTable.NewRow();
row3["OrderId"] = "O0003";
row3["OrderDate"] = new DateTime(2013, 3, 20);
orderTable.Rows.Add(row3);
} private static void InsertOrderDetails(DataTable orderDetailTable)
{
// Use an Object array to insert all the rows .
// Values in the array are matched sequentially to the columns, based on the order in which they appear in the table.
Object[] rows = {
new Object[]{1,"O0001","Mountain Bike",1419.5,36},
new Object[]{2,"O0001","Road Bike",1233.6,16},
new Object[]{3,"O0001","Touring Bike",1653.3,32},
new Object[]{4,"O0002","Mountain Bike",1419.5,24},
new Object[]{5,"O0002","Road Bike",1233.6,12},
new Object[]{6,"O0003","Mountain Bike",1419.5,48},
new Object[]{7,"O0003","Touring Bike",1653.3,8},
}; foreach (Object[] row in rows)
{
orderDetailTable.Rows.Add(row);
}
} private static void ShowTable(DataTable table)
{
foreach (DataColumn col in table.Columns)
{
Console.Write("{0,-14}", col.ColumnName);
}
Console.WriteLine(); foreach (DataRow row in table.Rows)
{
foreach (DataColumn col in table.Columns)
{
if (col.DataType.Equals(typeof(DateTime)))
Console.Write("{0,-14:d}", row[col]);
else if (col.DataType.Equals(typeof(Decimal)))
Console.Write("{0,-14:C}", row[col]);
else
Console.Write("{0,-14}", row[col]);
}
Console.WriteLine();
}
Console.WriteLine();
}
}

C# DataTable 类使用的更多相关文章

  1. C#操作DataTable类

    一.DataTable简介 (1)构造函数 名称 说明 DataTable()  不带参数初始化DataTable 类的新实例 DataTable(string tableName) 用指定的表名初始 ...

  2. 【转载】C#的DataTable类Clone及Copy方法的区别

    在C#中的Datatable类中,Clone方法和Copy方法都可以用来复制当前的DataTable对象,但DataTable类中的Clone方法和Copy方法还是有区别的,Clone方法只复制结构信 ...

  3. ADO.NET中DataTable类的使用

    DataTable类将关系数据表示为表格形式.在创建DataTable之前,必须包含System.Data名称空间.ADO.NET提供了一个DataTable类来独立创建和使用数据表.它也可以和Dat ...

  4. DataTable类

    DataTable是一个使用非常多的类,记得我在刚刚开始学习.Net的时候就已经了解并用过这个类,但如今再来看看,才发现这个类非常之复杂,复杂表现在哪些地方呢?主要是这个类与其他很多类都有关联,也就是 ...

  5. C#使用DataSet类、DataTable类、DataRow类、OleDbConnection类、OleDbDataAdapter类编写简单数据库应用

    //注意:请使用VS2010打开以下的源代码. //源代码地址:http://pan.baidu.com/s/1j9WVR using System; using System.Collections ...

  6. NPOI将xls文件解析为DataTable类数据

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...

  7. C# DataTable的詳細用法

    转载别人的转载,原作者都不知道了 在项目中经常用到DataTable,如果DataTable使用得当,不仅能使程序简洁实用,而且能够提高性能,达到事半功倍的效果,现对DataTable的使用技巧进行一 ...

  8. 深入详解DataTable

    在学习DataTable知识之前,我们有必要了解下ADO.NET.以下摘自MSDN: ADO.NET 对 Microsoft SQL Server 和 XML 等数据源以及通过 OLE DB 和 XM ...

  9. DataTable详解,以及dataview

    原文地址:http://www.cnblogs.com/moss_tan_jun/archive/2010/09/20/1832131.html 得到DataTable 得到DataTable有许多方 ...

  10. DataTable使用技巧总结【转】

    一.DataTable简介 ()构造函数 DataTable() 不带参数初始化DataTable 类的新实例. DataTable(string tableName) 用指定的表名初始化DataTa ...

随机推荐

  1. php7.4.x~php8.0.x 新特性

    PHP 核心中的新特性 命名参数 新增 命名参数 的功能. // array_fill(int $start_index, int $count, mixed $value): array // 使用 ...

  2. zustand:基于hooks的react状态管理

    react的状态管理 状态(State)是 React 中用于存储组件数据的特殊对象,它可以影响组件的渲染输出.状态管理的核心目标是确保数据的一致性.可预测性以及组件之间的数据流. 每个 React ...

  3. 从Delphi到Lazarus——我的编程之路

    今天终于下定决心,把我使用的编程环境从Delphi转变成Lazarus了.这也许是一个明智的选择,但做出这个决定的过程包含了辛酸和无奈. 这应该是我第三次安装Lazarus了.以前安装之后总是感觉有很 ...

  4. Gitlab的备份与恢复,异机转移

    ​注意:异机转移的时候,gitlab的版本必须一致. 一.备份GitLab数据 停止GitLab服务 gitlab-ctl stop unicorn gitlab-ctl stop sidekiq 创 ...

  5. PG 实现 Dynamic SQL

    CREATE OR REPLACE FUNCTION public.exec( text) RETURNS SETOF RECORD LANGUAGE 'plpgsql' AS $BODY$ BEGI ...

  6. 开源架构Fabric、FISCO BCOS(以下简称“BCOS”)、CITA 技术对比

    转自 https://www.coingogo.com/news/41300 联盟链技术哪家强?开源架构Fabric.FISCO BCOS(以下简称"BCOS").CITA 技术对 ...

  7. Qt音视频开发1-vlc解码播放

    一.前言 最开始接触视频监控这块的时候,用的就是vlc作为解码的内核,主要是因为vlc使用简单方便,直接传入一个句柄即可,简单几行代码就可以实现一个视频流播放,很适合初学者使用,也推荐初学者用qt+v ...

  8. 主打一个“小巧灵动”:Vite + Svelte

    作者:来自 vivo 互联网大前端团队-  Wei Xing 在研发小型项目时,传统的 Vue.React 显得太"笨重".本文主要针对开发小型项目的场景,谈谈 Vite+Svel ...

  9. 使用Halcon软件和圆形标定板进行相机标定的步骤和教程

    直接给出使用Halcon软件和圆形标定板进行相机标定的教学视频链接: 55-相机标定4-DLT,张正友标定法,Halcon标定算子

  10. Java实现拍卖系统详解

    一.项目背景与需求分析 随着互联网技术的飞速发展,电子商务领域不断拓展新的业务模式,在线拍卖系统应运而生并逐渐成为一种重要的商业交易方式.在当今数字化的时代,人们越来越倾向于通过网络平台进行各类交易活 ...