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
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Copy_LINQ_to_DataTable.WebForm1" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:GridView ID="GridView1" runat="server"></asp:GridView>
- </div>
- </form>
- </body>
- </html>
WebForm1.aspx.cs
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- namespace Copy_LINQ_to_DataTable
- {
- public partial class WebForm1 : System.Web.UI.Page
- {
- SchoolManagementEntities objSchoolManagementEntities = new SchoolManagementEntities();
-
- DataTable dt = new DataTable();
- protected void Page_Load(object sender, EventArgs e)
- {
-
- var query = from r in objSchoolManagementEntities.Students select r;
-
- dt.Columns.Add("FirstName", typeof(String));
- dt.Columns.Add("LastName", typeof(String));
-
- foreach (var p in query)
- {
- DataRow dr = dt.NewRow();
-
- dr["FirstName"] = p.FirstName;
- dr["LastName"] = p.LastName;
-
- dt.Rows.Add(dr);
- }
-
- GridView1.DataSource = dt;
- GridView1.DataBind();
- }
- }
- }
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!