AYUDA .NET

C# DataTable (Tutorial de Funcionamiento para Desarrolladores)

Bienvenido a este tutorial sobre C# DataTables. Un DataTable es una estructura de datos poderosa proporcionada por el marco .NET, que te permite almacenar, manipular y consultar datos en un formato tabular. En este tutorial, exploraremos los aspectos básicos de DataTables en C#, incluyendo la creación y modificación de DataTables, la adición de columnas y filas, la consulta de datos y el uso de DataView para filtrar y ordenar.

Al final de este tutorial, tendrás una buena comprensión de cómo utilizar DataTables en tus aplicaciones C#. ¡Comencemos!

Creación de una DataTable

Para crear un DataTable en C#, primero necesitas importar el espacio de nombres System.Data. Este espacio de nombres contiene varias clases y métodos relacionados con la manipulación de datos, incluida la clase DataTable.

 using System.Data;
 using System.Data;
Imports System.Data
$vbLabelText   $csharpLabel

A continuación, puede crear una instancia de la clase DataTable. La forma más sencilla de hacerlo es utilizando el constructor por defecto, así:

DataTable dt = new DataTable();
DataTable dt = new DataTable();
Dim dt As New DataTable()
$vbLabelText   $csharpLabel

También puedes crear un DataTable con un nombre específico pasando un parámetro de cadena al constructor:

DataTable dt = new DataTable("Employees");
DataTable dt = new DataTable("Employees");
Dim dt As New DataTable("Employees")
$vbLabelText   $csharpLabel

Métodos de DataTable

Añadir columnas

Una vez que haya creado una DataTable, puede empezar a añadirle columnas. Para agregar una columna, primero necesitas crear una instancia de la clase DataColumn y establecer sus propiedades, como ColumnName y DataType.

He aquí un ejemplo de cómo añadir tres columnas a una 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)
$vbLabelText   $csharpLabel

Puedes agregar múltiples columnas como la columna Id en la tabla de datos.

Añadir filas de datos

Después de definir las columnas, puedes comenzar a agregar filas al DataTable. Para agregar una fila, necesitas crear una nueva instancia de la clase DataRow y completar sus campos con los datos requeridos.

Aquí tienes un ejemplo de cómo agregar una nueva fila a un 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)
$vbLabelText   $csharpLabel

También puedes añadir múltiples filas de DataTable a la vez utilizando el mismo método en un bucle.

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
$vbLabelText   $csharpLabel

En el código anterior, hemos añadido tres filas de datos.

Acceso a los datos

Puede acceder a los datos almacenados en un DataTable iterando a través de sus colecciones de Rows y Columns. Aquí tienes un ejemplo de cómo mostrar el contenido de un DataTable en la consola:

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
$vbLabelText   $csharpLabel

Modificación de datos

Puedes modificar los datos en un DataTable actualizando los valores en sus objetos DataRow. He aquí un ejemplo de cómo actualizar la edad de un empleado concreto:

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
$vbLabelText   $csharpLabel

Borrar filas

Puedes eliminar una fila de un DataTable llamando al método Delete en un objeto DataRow:

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
$vbLabelText   $csharpLabel

Ten en cuenta que llamar a Delete en un DataRow solo marca la fila para eliminación. Necesitas llamar al método AcceptChanges en el DataTable para eliminar de manera permanente las filas borradas.

Gestión de varias tablas

En algunos casos, puede que necesite trabajar con varias tablas de datos simultáneamente. Puede crear una variable dataset para almacenar varios objetos DataTable y gestionar las relaciones entre ellos.

Consulta de datos con LINQ

LINQ (Language Integrated Query) es una función poderosa en C# que te permite consultar datos de diversas fuentes de datos, incluyendo objetos DataTable. Para usar LINQ con DataTables, necesitas importar el espacio de nombres System.Linq. He aquí un ejemplo de cómo filtrar empleados mayores de 25 años utilizando 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
$vbLabelText   $csharpLabel

DataView: Ordenar y filtrar

DataView es otra clase útil proporcionada por el espacio de nombres System.Data que te permite crear una vista ordenada o filtrada de un DataTable. Esto es especialmente útil cuando necesitas mostrar los datos en un control de interfaz de usuario como un DataGridView. También podemos realizar el enlace de datos para agregar datos al control DataGridView desde un DataTable.

He aquí un ejemplo de cómo crear un DataView para filtrar y ordenar los empleados en función de su edad:

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
$vbLabelText   $csharpLabel

Exportación de DataTable a PDF con IronPDF

IronPDF es un potente convertidor de HTML a PDF, lleno de funciones de manipulación de PDF fáciles de usar, que permite a los desarrolladores crear, leer y editar documentos PDF dentro de aplicaciones .NET.

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
$vbLabelText   $csharpLabel

En esta sección, aprenderemos cómo exportar un DataTable a un documento PDF usando IronPDF.

En primer lugar, debe instalar el paquete IronPDF NuGet. Abra la consola del gestor de paquetes en Visual Studio y ejecute el siguiente comando:

Install-Package IronPdf

Una vez instalado el paquete, puede empezar importando los espacios de nombres necesarios en su código:

using IronPdf;
using System.IO;
using IronPdf;
using System.IO;
Imports IronPdf
Imports System.IO
$vbLabelText   $csharpLabel

A continuación, cree un método auxiliar que convierta DataTable en una tabla HTML, ya que IronPDF utiliza HTML para representar el contenido de los documentos 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
$vbLabelText   $csharpLabel

Ahora, puedes usar la clase HtmlToPdf proporcionada por IronPDF para renderizar la tabla HTML y guardarla como un archivo 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
$vbLabelText   $csharpLabel

El método ExportDataTableToPdf crea un DataTable a partir de la tabla HTML y lo guarda en el archivo PDF.

Finalmente, llama al método ExportDataTableToPdf con los parámetros apropiados para exportar tu DataTable:

string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
string pdfOutputPath = "Employees.pdf";
ExportDataTableToPdf(dt, pdfOutputPath);
Dim pdfOutputPath As String = "Employees.pdf"
ExportDataTableToPdf(dt, pdfOutputPath)
$vbLabelText   $csharpLabel

Esto creará un archivo PDF llamado "Employees.pdf" que contiene el contenido de su DataTable en un formato tabular.

DataTable de C# (Cómo funciona para desarrolladores Tutorial) - Figura 1

Conclusión

En este tutorial, has aprendido los conceptos básicos de DataTables en C# y cómo exportar un DataTable a un documento PDF usando la biblioteca IronPDF. Al incorporar la columna de clave principal, las variables del conjunto de datos y DataView para filtrar y ordenar, tendrá un mayor control y flexibilidad sobre sus datos. Ahora debería tener un buen conocimiento de DataTables y de cómo utilizar IronPDF junto con DataTables para crear informes PDF de aspecto profesional en sus aplicaciones C#.

IronPDF ofrece una prueba gratuita de sus funciones, permitiéndote explorar sus capacidades antes de comprometerte a una compra.

Chipego
Ingeniero de software
Chipego tiene una habilidad natural para escuchar que le ayuda a comprender los problemas de los clientes y a ofrecer soluciones inteligentes. Se unió al equipo de Iron Software en 2023, después de estudiar una licenciatura en Tecnología de la Información. IronPDF e IronOCR son los dos productos en los que Chipego se ha centrado, pero su conocimiento de todos los productos crece día a día, a medida que encuentra nuevas formas de ayudar a los clientes. Disfruta de lo colaborativa que es la vida en Iron Software, con miembros del equipo de toda la empresa que aportan su variada experiencia para contribuir a soluciones eficaces e innovadoras. Cuando Chipego está lejos de su escritorio, a menudo se le puede encontrar disfrutando de un buen libro o jugando al fútbol.
< ANTERIOR
Instalar NuGet Powershell (Tutorial de cómo funciona para desarrolladores)
SIGUIENTE >
Cómo utilizar .NET Fiddle en C#