C# DataTable 类使用
命名空间:
程序集:
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 类使用的更多相关文章
- C#操作DataTable类
一.DataTable简介 (1)构造函数 名称 说明 DataTable() 不带参数初始化DataTable 类的新实例 DataTable(string tableName) 用指定的表名初始 ...
- 【转载】C#的DataTable类Clone及Copy方法的区别
在C#中的Datatable类中,Clone方法和Copy方法都可以用来复制当前的DataTable对象,但DataTable类中的Clone方法和Copy方法还是有区别的,Clone方法只复制结构信 ...
- ADO.NET中DataTable类的使用
DataTable类将关系数据表示为表格形式.在创建DataTable之前,必须包含System.Data名称空间.ADO.NET提供了一个DataTable类来独立创建和使用数据表.它也可以和Dat ...
- DataTable类
DataTable是一个使用非常多的类,记得我在刚刚开始学习.Net的时候就已经了解并用过这个类,但如今再来看看,才发现这个类非常之复杂,复杂表现在哪些地方呢?主要是这个类与其他很多类都有关联,也就是 ...
- C#使用DataSet类、DataTable类、DataRow类、OleDbConnection类、OleDbDataAdapter类编写简单数据库应用
//注意:请使用VS2010打开以下的源代码. //源代码地址:http://pan.baidu.com/s/1j9WVR using System; using System.Collections ...
- NPOI将xls文件解析为DataTable类数据
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.I ...
- C# DataTable的詳細用法
转载别人的转载,原作者都不知道了 在项目中经常用到DataTable,如果DataTable使用得当,不仅能使程序简洁实用,而且能够提高性能,达到事半功倍的效果,现对DataTable的使用技巧进行一 ...
- 深入详解DataTable
在学习DataTable知识之前,我们有必要了解下ADO.NET.以下摘自MSDN: ADO.NET 对 Microsoft SQL Server 和 XML 等数据源以及通过 OLE DB 和 XM ...
- DataTable详解,以及dataview
原文地址:http://www.cnblogs.com/moss_tan_jun/archive/2010/09/20/1832131.html 得到DataTable 得到DataTable有许多方 ...
- DataTable使用技巧总结【转】
一.DataTable简介 ()构造函数 DataTable() 不带参数初始化DataTable 类的新实例. DataTable(string tableName) 用指定的表名初始化DataTa ...
随机推荐
- apisix~路由前缀的正则匹配
参考:https://apisix.apache.org/zh/docs/apisix/FAQ/ 在你提供的 Apache APISIX 路由配置中,vars 字段用于定义一些变量匹配规则.具体来说, ...
- ELASTICSEARCH 读写性能优化
ELASTIC 写i性能优化 refresh translog flush refresh 优化 translog优化 flush 优化 读性能优化 shard 设置
- Vue3 组合式API
1.入口 创建实例时,配置setup方法,然后其内部书写组合式API代码,通过组合式API生产的数据和返回,需要暴漏出去才能给HTML使用 <script> //组合式(解构赋值) con ...
- Python版本与Jupyter记录
最近使用Python的时候,遇到一个版本问题.我本地安装的Python版本是3.8.0,在使用match...case...语法时,提示如下报错: 查询之后,才知晓3.8.0还没有match语法,ma ...
- winform窗体无边框拖动
1:引用命名空间 using System.Runtime.InteropServices; 2:想要拖动窗体的控件绑定MouseDown事件 点击查看代码 //窗体移动 [DllImport(&qu ...
- 如何在 duxapp 中开发一个兼容 RN 的动画库
Taro 一直以来都没有一个能兼容 RN 的动画方案,duxapp 中扩展了 createAnimation 方法,让这个方法兼容了 RN 端,下面让我们来看看实现思路 createAnimation ...
- nodejs版本控制器nvm安装及简单使用
介绍:nvm是node.js的版本管理器,可以安装和切换不同版本node.js 下载:https://github.com/coreybutler/nvm-windows/releases 官网下载: ...
- MYSQL8给新用户grant权限报错的解决方法
MYSQL8用客户端创建用户,无法grant,报错:Access denied for user 'root'@'xxx.xxx.xxx.xxx' (using password: YES) . 解 ...
- Shiro简单入门+个人理解
身为一个刚刚进入开发行业的学生,进入公司就开始了Shiro框架的应用,特此在这里写下收获. Shiro是apache旗下一个开源安全框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证,权 ...
- 探索使用 ViewContainerRef 的 Angular DOM 操控技术
探索使用 ViewContainerRef 的 Angular DOM 操控技术 https://indepth.dev/posts/1052/exploring-angular-dom-manipu ...