Introduction

This article shows how a LINQ query result can be converted to a datatable and later how the datatable can be consumed depending on the requirements.

Create ASP.Net web application

WebForm1.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Copy_LINQ_to_DataTable.WebForm1" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <title></title>
  6. </head>
  7. <body>
  8. <form id="form1" runat="server">
  9. <div>
  10. <asp:GridView ID="GridView1" runat="server"></asp:GridView>
  11. </div>
  12. </form>
  13. </body>
  14. </html>

WebForm1.aspx.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.UI;
  7. using System.Web.UI.WebControls;
  8. namespace Copy_LINQ_to_DataTable
  9. {
  10. public partial class WebForm1 : System.Web.UI.Page
  11. {
  12. SchoolManagementEntities objSchoolManagementEntities = new SchoolManagementEntities();
  13. DataTable dt = new DataTable();
  14. protected void Page_Load(object sender, EventArgs e)
  15. {
  16. var query = from r in objSchoolManagementEntities.Students select r;
  17. dt.Columns.Add("FirstName", typeof(String));
  18. dt.Columns.Add("LastName", typeof(String));
  19. foreach (var p in query)
  20. {
  21. DataRow dr = dt.NewRow();
  22. dr["FirstName"] = p.FirstName;
  23. dr["LastName"] = p.LastName;
  24. dt.Rows.Add(dr);
  25. }
  26. GridView1.DataSource = dt;
  27. GridView1.DataBind();
  28. }
  29. }
  30. }

The output of the application looks like this:

Summary

In this article we saw how a LINQ query can be converted into a DataTable. Happy coding!