.NET 帮助

C# DataTable(开发者教程:它是如何工作的)

发布 2023年五月8日
分享:

欢迎阅读本 C# 数据表教程。数据表 "是 .NET 框架提供的一种功能强大的数据结构,它允许您以表格格式存储、操作和查询数据。在本教程中,我们将探讨 C# 中 DataTables 的基础知识,包括创建和修改 DataTables、添加列和行、查询数据以及使用 DataView 进行筛选和排序。

本教程结束时,您将对如何在 C# 应用程序中使用 DataTables 有一个很好的了解。让我们开始吧!

创建数据表

要在 C# 中创建一个 DataTable,首先需要导入 System.Data 命名空间。该命名空间包含与数据操作有关的各种类和方法,其中包括 DataTable 类。

 using System.Data;
 using System.Data;
Imports System.Data
VB   C#

接下来,可以创建一个 DataTable 类的实例。最简单的方法是使用默认构造函数,例如

DataTable dt = new DataTable();
DataTable dt = new DataTable();
Dim dt As New DataTable()
VB   C#

您还可以通过向构造函数传递字符串参数,创建具有特定名称的 DataTable

DataTable dt = new DataTable("Employees");
DataTable dt = new DataTable("Employees");
Dim dt As New DataTable("Employees")
VB   C#

数据表方法

添加列

创建 DataTable 后,就可以开始添加列了。要添加列,首先需要创建一个 DataColumn 类的实例,并设置其属性,如 ColumnNameDataType

下面是一个如何向 DataTable 添加三列的示例:

DataColumn idColumn = new DataColumn("Id", typeof(int));
DataColumn nameColumn = new DataColumn("Name", typeof(string));
DataColumn ageColumn = new DataColumn("Age", typeof(int));

dt.Columns.Add(idColumn);
dt.Columns.Add(nameColumn);
dt.Columns.Add(ageColumn);
DataColumn idColumn = new DataColumn("Id", typeof(int));
DataColumn nameColumn = new DataColumn("Name", typeof(string));
DataColumn ageColumn = new DataColumn("Age", typeof(int));

dt.Columns.Add(idColumn);
dt.Columns.Add(nameColumn);
dt.Columns.Add(ageColumn);
Dim idColumn As New DataColumn("Id", GetType(Integer))
Dim nameColumn As New DataColumn("Name", GetType(String))
Dim ageColumn As New DataColumn("Age", GetType(Integer))

dt.Columns.Add(idColumn)
dt.Columns.Add(nameColumn)
dt.Columns.Add(ageColumn)
VB   C#

您可以添加多个列,如数据表中的 Id 列。

添加数据行

定义完列后,就可以开始向 DataTable 添加行了。要添加一行,需要创建一个新的 DataRow 类实例,并在其字段中填入所需的数据。

下面是一个如何在 DataTable 中添加新行的示例:

DataRow newRow = dt.NewRow();

newRow ["Id"] = 1;
newRow ["Name"] = "John Doe";
newRow ["Age"] = 30;

dt.Rows.Add(newRow);
DataRow newRow = dt.NewRow();

newRow ["Id"] = 1;
newRow ["Name"] = "John Doe";
newRow ["Age"] = 30;

dt.Rows.Add(newRow);
Dim newRow As DataRow = dt.NewRow()

newRow ("Id") = 1
newRow ("Name") = "John Doe"
newRow ("Age") = 30

dt.Rows.Add(newRow)
VB   C#

您还可以在一个循环中使用相同的方法一次添加多条 DataTable 行。

for (int i = 1; i <= 3; i++)
{
    DataRow row = dt.NewRow();
    row ["Id"] = i;
    row ["Name"] = "Employee " + i;
    row ["Age"] = 20 + i;
    dt.Rows.Add(row);
}
for (int i = 1; i <= 3; i++)
{
    DataRow row = dt.NewRow();
    row ["Id"] = i;
    row ["Name"] = "Employee " + i;
    row ["Age"] = 20 + i;
    dt.Rows.Add(row);
}
For i As Integer = 1 To 3
	Dim row As DataRow = dt.NewRow()
	row ("Id") = i
	row ("Name") = "Employee " & i
	row ("Age") = 20 + i
	dt.Rows.Add(row)
Next i
VB   C#

在上述代码中,我们添加了三行数据。

获取数据

你可以通过遍历 RowsColumns 集合来访问存储在DataTable中的数据。下面是一个如何在控制台中显示 DataTable 内容的示例:

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn col in dt.Columns)
    {
        Console.Write(row [col] + "\t");
    }
    Console.WriteLine();
}
foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn col in dt.Columns)
    {
        Console.Write(row [col] + "\t");
    }
    Console.WriteLine();
}
Imports Microsoft.VisualBasic

For Each row As DataRow In dt.Rows
	For Each col As DataColumn In dt.Columns
		Console.Write(row (col) & vbTab)
	Next col
	Console.WriteLine()
Next row
VB   C#

修改数据

您可以通过更新DataRow对象中的值来修改DataTable中的数据。下面是一个如何更新特定雇员年龄的示例:

DataRow employeeRow = dt.Rows.Find(1); // Find the row with the specified primary key
if (employeeRow != null)
{
    employeeRow ["Age"] = 35;
}
DataRow employeeRow = dt.Rows.Find(1); // Find the row with the specified primary key
if (employeeRow != null)
{
    employeeRow ["Age"] = 35;
}
Dim employeeRow As DataRow = dt.Rows.Find(1) ' Find the row with the specified primary key
If employeeRow IsNot Nothing Then
	employeeRow ("Age") = 35
End If
VB   C#

删除行

通过调用 DataRow 对象上的 Delete 方法,可以从 DataTable 中删除一行:

DataRow employeeRow = dt.Rows.Find(1);
if (employeeRow != null)
{
    employeeRow.Delete();
    dt.AcceptChanges(); // Commit the deletion
}
DataRow employeeRow = dt.Rows.Find(1);
if (employeeRow != null)
{
    employeeRow.Delete();
    dt.AcceptChanges(); // Commit the deletion
}
Dim employeeRow As DataRow = dt.Rows.Find(1)
If employeeRow IsNot Nothing Then
	employeeRow.Delete()
	dt.AcceptChanges() ' Commit the deletion
End If
VB   C#

请记住,在 DataRow 上调用 Delete 只能标记要删除的行。要永久删除已删除的行,需要调用 DataTable 上的 AcceptChanges 方法。

管理多个表

在某些情况下,您可能需要同时处理多个数据表。您可以创建一个数据集变量来存储多个 DataTable 对象,并管理它们之间的关系。

使用 LINQ 查询数据

LINQ (语言综合查询) 是 C# 中的一项强大功能,它允许您从各种数据源(包括 DataTable 对象)中查询数据。要在 DataTable 中使用 LINQ,需要导入 System.Linq 命名空间。下面是一个如何使用 LINQ 过滤 25 岁以上员工的示例:

using System.Linq;

var filteredRows = dt.AsEnumerable().Where(row => row.Field<int>("Age") > 25);

foreach (DataRow row in filteredRows)
{
    Console.WriteLine(row ["Name"]);
}
using System.Linq;

var filteredRows = dt.AsEnumerable().Where(row => row.Field<int>("Age") > 25);

foreach (DataRow row in filteredRows)
{
    Console.WriteLine(row ["Name"]);
}
Imports System.Linq

Private filteredRows = dt.AsEnumerable().Where(Function(row) row.Field(Of Integer)("Age") > 25)

For Each row As DataRow In filteredRows
	Console.WriteLine(row ("Name"))
Next row
VB   C#

DataView:排序和筛选

DataView "是 "System.Data "命名空间提供的另一个有用的类,它允许您创建 "DataTable "的排序或过滤视图。当您需要在 DataGridView 等 UI 控件中显示数据时,这个类尤其有用。我们还可以进行数据绑定,从DataTableDataGridView控件添加数据。

下面是一个示例,说明如何创建一个数据视图,根据员工的年龄对其进行筛选和排序:

DataView view = new DataView(dt);

// Filter employees older than 25
view.RowFilter = "Age > 25";

// Sort by age in descending order
view.Sort = "Age DESC";

// Display the filtered and sorted data
foreach (DataRowView rowView in view)
{
    DataRow row = rowView.Row;
    Console.WriteLine(row ["Name"]);
}
DataView view = new DataView(dt);

// Filter employees older than 25
view.RowFilter = "Age > 25";

// Sort by age in descending order
view.Sort = "Age DESC";

// Display the filtered and sorted data
foreach (DataRowView rowView in view)
{
    DataRow row = rowView.Row;
    Console.WriteLine(row ["Name"]);
}
Dim view As New DataView(dt)

' Filter employees older than 25
view.RowFilter = "Age > 25"

' Sort by age in descending order
view.Sort = "Age DESC"

' Display the filtered and sorted data
For Each rowView As DataRowView In view
	Dim row As DataRow = rowView.Row
	Console.WriteLine(row ("Name"))
Next rowView
VB   C#

使用 IronPDF 将 DataTable 导出为 PDF

IronPDF 是一个强大的 HTML 转 PDF 该转换器具有用户友好的 PDF 操作功能,使开发人员能够在 .NET 应用程序中创建、阅读和编辑 PDF 文档。

using IronPdf;

class Program
{
    static void Main(string [] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string [] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

在本节中,我们将学习如何使用 IronPDF 将 "数据表 "导出为 PDF 文档。

首先,你需要安装 IronPDF NuGet 软件包。在 Visual Studio 中打开软件包管理器控制台,运行以下命令:

Install-Package IronPdf

安装软件包后,就可以开始在代码中导入必要的命名空间:

using IronPdf;
using System.IO;
using IronPdf;
using System.IO;
Imports IronPdf
Imports System.IO
VB   C#

接下来,创建一个辅助方法,将 DataTable 转换为 HTML 表格,因为 IronPDF 使用 HTML 来呈现 PDF 文档中的内容:

public static string ConvertDataTableToHtml(DataTable dt)
{
    StringBuilder htmlBuilder = new StringBuilder();

    htmlBuilder.AppendLine("<table border='1' cellpadding='5' cellspacing='0'>");
    htmlBuilder.AppendLine("<tr>");

    // Add column headers
    foreach (DataColumn col in dt.Columns)
    {
        htmlBuilder.AppendFormat("<th>{0}</th>", col.ColumnName);
    }

    htmlBuilder.AppendLine("</tr>");

    // Add rows
    foreach (DataRow row in dt.Rows)
    {
        htmlBuilder.AppendLine("<tr>");

        foreach (DataColumn col in dt.Columns)
        {
            htmlBuilder.AppendFormat("<td>{0}</td>", row [col]);
        }

        htmlBuilder.AppendLine("</tr>");
    }

    htmlBuilder.AppendLine("</table>");

    return htmlBuilder.ToString();
}
public static string ConvertDataTableToHtml(DataTable dt)
{
    StringBuilder htmlBuilder = new StringBuilder();

    htmlBuilder.AppendLine("<table border='1' cellpadding='5' cellspacing='0'>");
    htmlBuilder.AppendLine("<tr>");

    // Add column headers
    foreach (DataColumn col in dt.Columns)
    {
        htmlBuilder.AppendFormat("<th>{0}</th>", col.ColumnName);
    }

    htmlBuilder.AppendLine("</tr>");

    // Add rows
    foreach (DataRow row in dt.Rows)
    {
        htmlBuilder.AppendLine("<tr>");

        foreach (DataColumn col in dt.Columns)
        {
            htmlBuilder.AppendFormat("<td>{0}</td>", row [col]);
        }

        htmlBuilder.AppendLine("</tr>");
    }

    htmlBuilder.AppendLine("</table>");

    return htmlBuilder.ToString();
}
Public Shared Function ConvertDataTableToHtml(ByVal dt As DataTable) As String
	Dim htmlBuilder As New StringBuilder()

	htmlBuilder.AppendLine("<table border='1' cellpadding='5' cellspacing='0'>")
	htmlBuilder.AppendLine("<tr>")

	' Add column headers
	For Each col As DataColumn In dt.Columns
		htmlBuilder.AppendFormat("<th>{0}</th>", col.ColumnName)
	Next col

	htmlBuilder.AppendLine("</tr>")

	' Add rows
	For Each row As DataRow In dt.Rows
		htmlBuilder.AppendLine("<tr>")

		For Each col As DataColumn In dt.Columns
			htmlBuilder.AppendFormat("<td>{0}</td>", row (col))
		Next col

		htmlBuilder.AppendLine("</tr>")
	Next row

	htmlBuilder.AppendLine("</table>")

	Return htmlBuilder.ToString()
End Function
VB   C#

现在,您可以使用 HtmlToPdf 类来渲染 HTML 表格并将其保存为 PDF 文件:

public static void ExportDataTableToPdf(DataTable dt, string outputPath)
{
    // Convert DataTable to HTML
    string htmlTable = ConvertDataTableToHtml(dt);

    // Create a new HTML to PDF renderer
    var renderer = new ChromePdfRenderer();

    // Set global styles for the table
    renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
    renderer.RenderingOptions.FirstPageNumber = 1;

    // Render the HTML table as a PDF document
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlTable);

    // Save the PDF file
    pdf.SaveAs(outputPath);
}
public static void ExportDataTableToPdf(DataTable dt, string outputPath)
{
    // Convert DataTable to HTML
    string htmlTable = ConvertDataTableToHtml(dt);

    // Create a new HTML to PDF renderer
    var renderer = new ChromePdfRenderer();

    // Set global styles for the table
    renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
    renderer.RenderingOptions.FirstPageNumber = 1;

    // Render the HTML table as a PDF document
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlTable);

    // Save the PDF file
    pdf.SaveAs(outputPath);
}
Public Shared Sub ExportDataTableToPdf(ByVal dt As DataTable, ByVal outputPath As String)
	' Convert DataTable to HTML
	Dim htmlTable As String = ConvertDataTableToHtml(dt)

	' Create a new HTML to PDF renderer
	Dim renderer = New ChromePdfRenderer()

	' Set global styles for the table
	renderer.RenderingOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
	renderer.RenderingOptions.FirstPageNumber = 1

	' Render the HTML table as a PDF document
	Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlTable)

	' Save the PDF file
	pdf.SaveAs(outputPath)
End Sub
VB   C#

ExportDataTableToPdf "方法从 HTML 表格创建一个 "DataTable",并将其保存到 PDF 文件中。

最后,使用适当的参数调用 ExportDataTableToPdf 方法导出您的 DataTable

string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
Dim pdfOutputPath As String = "Employees.pdf"
ExportDataTableToPdf(dt, pdfOutputPath)
VB   C#

这将创建一个名为 "Employees.pdf "的 PDF 文件,其中包含表格格式的 "DataTable "内容。

C# DataTable(面向开发人员的工作原理教程) - 图 1

结论

在本教程中,您将学习到 C# 中 DataTable 的基础知识,以及如何使用 IronPDF 库将 "DataTable "导出为 PDF 文档。通过整合主键列、数据集变量以及用于过滤和排序的 DataView,您将对数据拥有更强的控制力和灵活性。现在,您应该对 DataTables 以及如何将 IronPDF 与 DataTables 结合使用以在 C# 应用程序中创建专业外观的 PDF 报告有了很好的了解。

IronPDF 提供了 免费试用这样,您就可以在购买前了解其特性和功能。

< 前一页
安装 NuGet Powershell(开发人员教程中的工作原理)
下一步 >
如何在C#中使用.NET Fiddle

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >