Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
Welcome to this tutorial on C# DataTables. A DataTable
is a powerful data structure provided by the .NET framework, which allows you to store, manipulate, and query data in a tabular format. In this tutorial, we will explore the basics of DataTables in C#, including creating and modifying DataTables
, adding columns and rows, querying data, and using DataView
for filtering and sorting.
By the end of this tutorial, you will have a good understanding of how to use DataTables
in your C# applications. Let's get started!
To create a DataTable
in C#, you first need to import the System.Data
namespace. This namespace contains various classes and methods related to data manipulation, including the DataTable
class.
using System.Data;
using System.Data;
Imports System.Data
Next, you can create an instance of the DataTable
class. The simplest way to do this is by using the default constructor, like so:
DataTable dt = new DataTable();
DataTable dt = new DataTable();
Dim dt As New DataTable()
You can also create a DataTable
with a specific name by passing a string parameter to the constructor:
DataTable dt = new DataTable("Employees");
DataTable dt = new DataTable("Employees");
Dim dt As New DataTable("Employees")
Once you have created a DataTable, you can start adding columns to it. To add a column, you first need to create an instance of the DataColumn
class and set its properties, such as ColumnName
and DataType
.
Here's an example of how to add three columns to a 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)
You can add multiple columns like the Id
column in the data table.
After defining the columns, you can start adding rows to the DataTable
. To add a row, you need to create a new instance of the DataRow
class and populate its fields with the required data.
Here's an example of how to add a new row to a 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)
You can also add multiple DataTable
rows at once using the same method in a loop.
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
In the above code, we added three data rows.
You can access the data stored in a DataTable
by iterating through its Rows
and Columns
collections. Here's an example of how to display the contents of a DataTable
in the console:
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
You can modify the data in a DataTable
by updating the values in its DataRow
objects. Here's an example of how to update the age of a specific employee:
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
You can delete a row from a DataTable by calling the Delete method on a DataRow
object:
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
Keep in mind that calling Delete
on a DataRow
only marks the row for deletion. You need to call the AcceptChanges
method on the DataTable
to permanently remove the deleted rows.
In some cases, you might need to work with multiple data tables simultaneously. You can create a dataset variable to store several DataTable objects and manage the relationships between them.
LINQ (Language Integrated Query) is a powerful feature in C# that allows you to query data from various data sources, including DataTable
objects. To use LINQ with DataTables, you need to import the System.Linq
namespace. Here's an example of how to filter employees older than 25 using LINQ:
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
DataView
is another useful class provided by the System.Data
namespace that allows you to create a sorted or filtered view of a DataTable
. This is especially useful when you need to display the data in a UI control like a DataGridView
. We can also do data binding to add data to the DataGridView
control from a DataTable
.
Here's an example of how to create a DataView to filter and sort the employees based on their age:
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
IronPDF is a powerful HTML to PDF converter, replete with user-friendly PDF-manipulation features, enabling developers to create, read, and edit PDF documents within .NET applications.
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
In this section, we will learn how to export a DataTable
to a PDF document using IronPDF.
First, you need to install the IronPDF NuGet package. Open the Package Manager Console in Visual Studio and run the following command:
Install-Package IronPdf
Once the package is installed, you can start by importing the necessary namespaces in your code:
using IronPdf;
using System.IO;
using IronPdf;
using System.IO;
Imports IronPdf
Imports System.IO
Next, create a helper method that converts the DataTable into an HTML table, as IronPDF uses HTML to render content in PDF documents:
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
Now, you can use the HtmlToPdf class
provided by IronPDF to render the HTML table and save it as a PDF file:
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
The ExportDataTableToPdf
method creates a DataTable
from the HTML table and saves it to the PDF file.
Finally, call the ExportDataTableToPdf
method with the appropriate parameters to export your DataTable
:
string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
Dim pdfOutputPath As String = "Employees.pdf"
ExportDataTableToPdf(dt, pdfOutputPath)
This will create a PDF file named "Employees.pdf" containing the contents of your DataTable
in a tabular format.
In this tutorial, you've learned the basics of DataTables in C# and how to export a DataTable
to a PDF document using the IronPDF library. By incorporating the primary key column, dataset variables, and DataView for filtering and sorting, you will have greater control and flexibility over your data. Now you should have a good understanding of DataTables and how to use IronPDF in conjunction with DataTables to create professional-looking PDF reports in your C# applications.
IronPDF offers a free trial of its features, allowing you to explore its capabilities before committing to a purchase.
9 .NET API products for your office documents