Convert LINQ Query to DataTable

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.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <asp:GridView ID="GridView1" runat="server"></asp:GridView>  
  13.     </div>  
  14.     </form>  
  15. </body>  
  16. </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.   
  9. namespace Copy_LINQ_to_DataTable  
  10. {  
  11.     public partial class WebForm1 : System.Web.UI.Page  
  12.     {  
  13.         SchoolManagementEntities objSchoolManagementEntities = new SchoolManagementEntities();  
  14.   
  15.         DataTable dt = new DataTable();  
  16.         protected void Page_Load(object sender, EventArgs e)  
  17.         {  
  18.   
  19.             var query = from r in objSchoolManagementEntities.Students select r;  
  20.               
  21.             dt.Columns.Add("FirstName"typeof(String));  
  22.             dt.Columns.Add("LastName"typeof(String));  
  23.               
  24.             foreach (var p in query)  
  25.             {  
  26.                 DataRow dr = dt.NewRow();  
  27.                   
  28.                 dr["FirstName"] = p.FirstName;  
  29.                 dr["LastName"] = p.LastName;  
  30.   
  31.                 dt.Rows.Add(dr);  
  32.             }  
  33.   
  34.             GridView1.DataSource = dt;  
  35.             GridView1.DataBind();  
  36.         }  
  37.     }  
  38. }  

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!


Recommended Free Ebook
Similar Articles
MVC Corporation
MVC Corporation is consulting and IT services based company.