.NET 도움말 C# DataTable (How It Works For Developers Tutorial) 커티스 차우 업데이트됨:6월 22, 2025 다운로드 IronPDF NuGet 다운로드 DLL 다운로드 윈도우 설치 프로그램 무료 체험 시작하기 LLM용 사본 LLM용 사본 LLM용 마크다운 형식으로 페이지를 복사하세요 ChatGPT에서 열기 ChatGPT에 이 페이지에 대해 문의하세요 제미니에서 열기 제미니에게 이 페이지에 대해 문의하세요 Grok에서 열기 Grok에게 이 페이지에 대해 문의하세요 혼란 속에서 열기 Perplexity에게 이 페이지에 대해 문의하세요 공유하다 페이스북에 공유하기 트위터에 공유하기 LinkedIn에 공유하기 URL 복사 이메일로 기사 보내기 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! Creating a DataTable 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; $vbLabelText $csharpLabel 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(); $vbLabelText $csharpLabel 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"); $vbLabelText $csharpLabel DataTable Methods Adding Columns 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); $vbLabelText $csharpLabel You can add multiple columns like the Id column in the data table. Adding Data Rows 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); $vbLabelText $csharpLabel 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); } $vbLabelText $csharpLabel In the above code, we added three data rows. Accessing Data 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(); } $vbLabelText $csharpLabel Modifying Data 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: var primaryKey = 1; DataRow employeeRow = dt.Rows.Find(primaryKey); // Find the row with the specified primary key if (employeeRow != null) { employeeRow["Age"] = 35; } var primaryKey = 1; DataRow employeeRow = dt.Rows.Find(primaryKey); // Find the row with the specified primary key if (employeeRow != null) { employeeRow["Age"] = 35; } $vbLabelText $csharpLabel Deleting Rows 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 } $vbLabelText $csharpLabel 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. Managing Multiple Tables 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. Querying Data with LINQ 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"]); } $vbLabelText $csharpLabel DataView: Sorting and Filtering 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"]); } $vbLabelText $csharpLabel Exporting DataTable to PDF with IronPDF 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(); // 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"); // 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"); // 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(); // 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"); // 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"); // Convert URL to PDF var url = "http://ironpdf.com"; // Specify the URL var pdfFromUrl = renderer.RenderUrlAsPdf(url); pdfFromUrl.SaveAs("URLToPDF.pdf"); } } $vbLabelText $csharpLabel 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; $vbLabelText $csharpLabel 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(); } $vbLabelText $csharpLabel 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); } $vbLabelText $csharpLabel 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); $vbLabelText $csharpLabel This will create a PDF file named "Employees.pdf" containing the contents of your DataTable in a tabular format. Conclusion 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. 자주 묻는 질문 C#의 데이터 테이블이란 무엇인가요? 데이터 테이블은 개발자가 데이터를 표 형식으로 저장, 조작 및 쿼리할 수 있게 해주는 .NET 프레임워크의 다목적 데이터 구조로, 애플리케이션에서 구조화된 데이터를 처리하는 데 필수적입니다. C#에서 데이터 테이블을 PDF 문서로 변환하려면 어떻게 해야 하나요? C#에서 데이터 테이블을 PDF 문서로 변환하려면 먼저 데이터 테이블을 HTML 테이블로 변환합니다. IronPDF의 HtmlToPdf 클래스를 사용하여 HTML을 PDF 문서로 렌더링하고 결과 파일을 저장합니다. C#에서 데이터 테이블은 어떻게 만들나요? C#에서 데이터 테이블을 만들려면 System.Data 네임스페이스를 가져오고 생성자를 사용하여 데이터 테이블 클래스를 인스턴스화하고, 선택적으로 데이터 테이블의 특정 이름을 제공해야 합니다. 데이터 테이블에 열을 추가하는 단계는 무엇인가요? 데이터 테이블에 열을 추가하려면 DataColumn 클래스의 인스턴스를 만들고, ColumnName 및 DataType과 같은 속성을 구성한 다음, 데이터 테이블의 열 컬렉션에 추가합니다. 보고용으로 데이터테이블의 데이터를 PDF로 내보내려면 어떻게 해야 하나요? 데이터테이블을 HTML 테이블 형식으로 변환하여 데이터테이블의 데이터를 PDF로 내보낸 다음 IronPDF를 사용하여 이 HTML을 PDF 문서로 렌더링하여 전문가 수준의 보고서를 만들 수 있습니다. C#에서 데이터 테이블에 행을 추가하려면 어떻게 하나요? C#에서 데이터 테이블에 행을 추가하려면 새 DataRow 인스턴스를 만들고 데이터로 채운 다음 데이터 테이블의 행 컬렉션에 추가합니다. 이 프로세스는 루프를 사용하여 여러 행에 대해 반복할 수 있습니다. LINQ란 무엇이며 DataTables와 함께 어떻게 사용할 수 있나요? LINQ(언어 통합 쿼리)는 데이터 테이블을 비롯한 다양한 소스의 데이터를 필터링, 정렬 및 조작하여 데이터 작업을 간소화할 수 있는 C#의 강력한 쿼리 도구입니다. 데이터뷰를 사용하여 데이터테이블을 필터링하고 정렬하려면 어떻게 해야 하나요? 데이터뷰는 데이터테이블의 필터링 또는 정렬된 보기를 만드는 편리한 방법을 제공합니다. 행 필터 및 정렬 속성을 설정하여 데이터가 표시되는 방식을 제어할 수 있으며, 이는 특히 UI 컴포넌트에서 유용합니다. 데이터 테이블을 PDF로 내보내는 데 필요한 라이브러리는 어떻게 설치하나요? 데이터 테이블을 PDF로 내보내는 데 필요한 IronPDF 라이브러리를 설치하려면 Visual Studio의 패키지 관리자 콘솔을 사용하여 다음 명령을 실행합니다: Install-Package IronPdf. 커티스 차우 지금 바로 엔지니어링 팀과 채팅하세요 기술 문서 작성자 커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다. 커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다. 관련 기사 업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기 업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기 업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기 Install NuGet Powershell (How it Works for Developers Tutorial)How to use .NET Fiddle in C#
업데이트됨 12월 11, 2025 Bridging CLI Simplicity & .NET : Using Curl DotNet with IronPDF Jacob Mellor has bridged this gap with CurlDotNet, a library created to bring the familiarity of cURL to the .NET ecosystem. 더 읽어보기
업데이트됨 12월 20, 2025 RandomNumberGenerator C# Using the RandomNumberGenerator C# class can help take your PDF generation and editing projects to the next level 더 읽어보기
업데이트됨 12월 20, 2025 C# String Equals (How it Works for Developers) When combined with a powerful PDF library like IronPDF, switch pattern matching allows you to build smarter, cleaner logic for document processing 더 읽어보기