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 ...
随机推荐
- 在自家的代码生成工具中,增加对跨平台WxPython项目的前端代码生成,简直方便的不得了
在经过长时间对WxPython的深入研究,并对其构建项目有深入的了解,以及完成对基础框架的完整改写后,终于在代码生成工具完全整合了基于 Python 跨平台方案项目的代码快速生成了,包括基于FastA ...
- Winform窗体控件双向绑定数据模拟读写PLC数据
1.用Modbus工具模拟PLC 2.创建一个实体类 点击查看代码 internal class Data : INotifyPropertyChanged { ushort[] ushorts = ...
- 《JavaScript 模式》读书笔记(4)— 函数3
这篇,我们来学习下自定义函数以及即时函数的内容. 四.自定义函数 函数可以动态定义,也可以分配给变量.如果创建了一个新函数,并且将其分配给保存了另外函数的同一个变量,那么就以一个新函数覆盖了旧函数.在 ...
- Vue中使用ref属性获取元素||组件标签
元素绑定属性 //绑定ref属性 <table ref="refTable"></table> 获取元素 //在方法内 this.$refs.refTabl ...
- 服务迁移之《tomcat性能优化》
删除无用的connector,因为一般的tomcat前面都会挂有nginx服务 增加connnector使用的线程池的数量 删除没有用的listener host优化项:autoDeploy设置为fa ...
- 4 步缩减 Script Evaluation Time
4 步缩减脚本评估时间 (Script Evaluation Time) https://touch.marfeel.com/resources/blog/reduce-script-evaluati ...
- eShopOnContainer 中 unauthorized_client error 登录错误处理
在准备好 eShopOnContainer 环境,运行起来之后,不幸的是,我遇到了不能登录的错误. 从错误信息中,可以看到 unauthorized_client 的内容.这是为什么呢? 从 eSho ...
- 在app內建web server
这几年在三家企业都使用 app 內建 web server 的技术方案.效果很好. 该方案顾名思义,就是在 app 中加入一个 embed webserver 组件.组件和app运行于同一进程空间.程 ...
- Java的HTTP接口测试框架Gatling
之前讲过的<JHM>是一个java的基准测试框架,一般用于测试jdk里的API.如果要测试http接口,可以使用Gatling. 你可能用过JMeter,也是可以的 原生的Gatling是 ...
- sed 指定行后或行前插入
sed 功能非常强大,这里主要列出一些工作中常用到的举例,以后再追加 示例文本 example.cfg Config = { a = 1, b = 1024, c = { ErrLevel = 4, ...