In this article, we will discuss about the Linq implementation in Gridview. The below example is one way to implement the Linq Concept in Asp.net.

First create the dbml file,Go to the App_Code Folder then right click your subfolder to Add New Item to choose the LinQ to SQL Classes and create a Table by right click and Add -> Class Or to user Server Explorer to drag and drop the Table. Then mention the namespace in Properties window like below,


Second to create a Business Logic to implement your requirements. Here I have used the select Operations. Below code will give clarity


BusinessLayer


using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


namespace BL
{
public class TestLinQPL
{
public string MenuID { get; set; }
public string MenuName { get; set; }
public string ParentMenuId { get; set; }
public string Status { get; set; }
}

public class TestLingBL : TestLinQPL
{
private string sFilter = string.Empty;

public IQueryable BindMenu(int startRowIndex, int maximumRows, string MenuName)
{
if (MenuName == null)
{
return null;
}
else
{
if (MenuName != "~~")
sFilter = MenuName;
DBContext.TestLinQDataContext dbContext = new DBContext.TestLinQDataContext(CommonBehavior.GetMainConnectionString());

// int sNo = 0;
var query = from User in dbContext.tmenus
//join Emp in dbContext.M_TestRole on User.UserID equals Emp.UserID
where User.MenuName.ToUpper().Contains(sFilter.ToUpper())
orderby User.MenuID
select new
{
    MenuID = User.MenuID,
    MenuName = User.MenuName,
    ParentMenuId = User.ParentMenuID,
    Status = User.Status
};
return query.Skip(startRowIndex).Take(maximumRows);
}
}

public int GetCount(string MenuName)
{
if (MenuName != "~~")
sFilter = MenuName;
DBContext.TestLinQDataContext dbContext = new DBContext.TestLinQDataContext(CommonBehavior.GetMainConnectionString());
return (from User in dbContext.tmenus
where User.MenuName.ToUpper().Contains(sFilter.ToUpper())
select User).Count();
}

}
}

Then we will go to our aspx Page to use the controls like below

TestLinQ.aspx



<asp:Content ID="Content1" ContentPlaceHolderID="cphPFPMaster" Runat="Server">

<script language="javascript" type="text/javascript">

var gridViewCtlId = '<%=gvTestBind.ClientID%>';    
var gridViewCtl = null;
var curSelRow = null;

function getGridViewControl()    
{        
if (null == gridViewCtl)        
{            
   gridViewCtl = document.getElementById(gridViewCtlId);        
}
}

function getSelectedRow(rowIdx) {
getGridViewControl();
if (null != gridViewCtl) {
    return gridViewCtl.rows[rowIdx];
}
return null;
}

function onGridViewRowSelected(rowIdx,GridViewID) {

gridViewCtl = document.getElementById(GridViewID);

if (null != gridViewCtl) {
    var selRow = gridViewCtl.rows[rowIdx];
    //var selRow = getSelectedRow(rowIdx + 1);
    var sID = selRow.cells[0].innerText;
    alert(sID);
    //window.opener.document.getElementById('<%=Request["lblUserID"]%>').value = sUserID;
    //self.close();
}
}
</script>

<table cellSpacing="0" cellPadding="0" width="100%">
<tr>
<td align="center">
<asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>
</td>
</tr>
<tr vAlign="top" >
<td align="center">
            <table cellSpacing="0" cellPadding="0" border="0" width="50%">
                        <tr vAlign="top">
                            <td  align="left">
                <asp:Label ID="lblName" runat="server" Text="Search Menu Name :"></asp:Label>
                    </td>
                    <td  align="left">
                  <asp:TextBox ID="tbSearchName" runat="server" CssClass="NormalTextBox"></asp:TextBox>
                    </td>
                    <td  align="left">
                  <asp:Button ID="btnSearch" runat="server" Text="Search"
                      onclick="btnSearch_Click" CssClass="Controls" style="margin-top:0px"/>
                    </td>
                        </tr>
            </table>
</td>
</tr>
<tr valign="top">
<td align="center">
<%--onrowcreated="gvTestBind_RowCreated" --%>
<asp:GridView ID="gvTestBind" DataSourceID="ObjectDataSource1" runat="server"
    CssClass="NormalGirdView" AllowPaging="True" CellSpacing="1" CellPadding="5" PageSize = "2"
     onrowdatabound="gvTestBind_RowDataBound">
    <AlternatingRowStyle BackColor="#DCE0E8"/>
    <HeaderStyle BackColor="#637687" HorizontalAlign="Center" ForeColor="White" Height="11PX" />
</asp:GridView>

<asp:ObjectDataSource ID="ObjectDataSource1" EnablePaging="true" runat="server"
SelectCountMethod="GetCount" SelectMethod="BindMenu"
TypeName="BL.TestLingBL"
    onselected="ObjectDataSource1_Selected"
    onselecting="ObjectDataSource1_Selecting" >
    <SelectParameters>
    <asp:Parameter Name="MenuName" Type="String" Direction="Input" />
    </SelectParameters>
</asp:ObjectDataSource>
<asp:HiddenField ID="HiddenField1" runat="server" />
</td>
</tr>

</table>

</asp:Content>


And then the code behind we just passes the parameter that is we add in the Data Source.

TestLinQ.aspx.cs


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Test_TestLinQ : System.Web.UI.Page
{
BL.TestLingBL  objMenu = new BL.TestLingBL();

protected void Page_Load(object sender, EventArgs e)
{
lblError.Text = string.Empty;
if (!IsPostBack)
{
    ObjectDataSource1.SelectParameters["LastName"].DefaultValue = tbSearchName.Text.Trim();
}
//if (!IsPostBack)
//{
//    List<BusinessLayer.EmployeeDemographic> listEmployeeDemographic = objMenu.GetEmployeeDemographic(tbSearchName.Text.Trim().Replace("'", "''"), null).ToList();
//    Page.Items.Add("DemographicEmployees",listEmployeeDemographic);
//}
}
protected void btnSearch_Click(object sender, EventArgs e)
{

if (tbSearchName.Text.Trim() == "")
    ObjectDataSource1.SelectParameters["LastName"].DefaultValue = "~~";
else
    ObjectDataSource1.SelectParameters["LastName"].DefaultValue = tbSearchName.Text.Trim();
gvEmployeeDemographicLookup.DataBind();
}

protected void gvEmployeeDemographicLookup_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Pager)
    e.Row.Cells[1].Visible = false;

if (e.Row.RowType == DataControlRowType.DataRow)
{
    e.Row.Attributes.Add("onclick", "javascript:onGridViewRowSelected('" + (e.Row.RowIndex + 1).ToString() + "','" + gvEmployeeDemographicLookup.ClientID + "')");
    e.Row.CssClass = "GridLink";
}

}

protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{

}
protected void ObjectDataSource1_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{

}
}


Suppose we hit the Search Button, it will call the button event to assign value to corresponding Parameter and ObjectDataSource1_Selecting event will be called, it will make a call of our Business layer that is configured in ObjectDatasource. Finally ObjectDataSource1_Selected called to assign a value to Grid and bind it.

The enduser screen is like below,




In this Article, we have Export the DataTable as a PDF/Excel/Word Format. I hope the below code is useful to us.

Aspx.cs File

Common.Report objReport = new Common.Report();
DataTable objReportTable = (DataTable)Session["ReportTable"];
if (objReportTable != null)
objReport.ShowReport(Common.ReportType.Excel, objReportTable, "TestExcel", objReportTable.Rows.Count, true);

using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Net;
using System.Web.UI;
using System.Drawing;
using HOV.Common.Export;


/// <summary>
/// Common Initialization / Functionality
/// </summary>

namespace Common
{

public enum ReportType
{
    PDF,
    Word,
    Excel
}

/// <summary>
/// Create the Generic Reports
/// </summary>
public class Report
{

public void ShowReport(ReportType rtExportType, DataTable dtReportTable, string TitleLabel, int iColumnsCount, bool bLandscape)
{
try
{
if (dtReportTable != null)
{
    if (dtReportTable.Rows.Count == 0)
    {
        DataRow drw = dtReportTable.NewRow();
        foreach (DataColumn clmn in dtReportTable.Columns)
        {
            try
            {
                drw[clmn] = " ";
            }
            catch (Exception)
            {
                drw[clmn] = 0;
            }
        }
        dtReportTable.Rows.Add(drw);
    }
    DataTable correctedDS = dtReportTable;
    Export(rtExportType, correctedDS.DefaultView, TitleLabel, iColumnsCount, bLandscape);
}
}
catch (Exception ex)
{
throw ex;
}
}

private string GetTitleLabel(string strTitleLabel)
{
//Regex.Replace(strTitleLabel, @"[^~!@#$%^&*()+=:;<>/\\|'\{}[]`]", "");
//return strTitleLabel.Trim();
return strTitleLabel.Replace(" ", "").Replace("~", "").Replace("!", "").Replace("@", "").Replace("#", "").Replace("$", "").Replace("%", "").Replace("^", "").Replace("&", "").Replace("*", "").Replace("(", "").Replace(")", "").Replace("+", "").Replace("=", "").Replace(":", "").Replace(";", "").Replace("<", "").Replace(">", "").Replace("/", "").Replace("\\", "").Replace("|", "").Replace("'", "").Replace("\"", "").Replace("{", "").Replace("}", "").Replace("[", "").Replace("]", "").Replace("`", "");
}

private void Export(ReportType rtExportType, DataView dvExportTable, string TitleLabel, int iColumnsCount, bool bLandscape)
{
try
{
string _sFileName = string.Empty;
HttpContext.Current.Response.Clear();
switch (rtExportType)
{
    case ReportType.PDF:
        HttpContext.Current.Response.ContentType = "application/pdf";
        _sFileName = GetTitleLabel(TitleLabel) + ".pdf";
        break;
    case ReportType.Excel:
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        _sFileName = GetTitleLabel(TitleLabel) + ".xls";
        break;
    case ReportType.Word:
        HttpContext.Current.Response.ContentType = "application/vnd.doc";
        _sFileName = GetTitleLabel(TitleLabel) + ".doc";
        break;
}
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + _sFileName);
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
HttpContext.Current.Response.Charset = "";
switch (rtExportType)
{
    case ReportType.PDF: //Pdf Report

GridView gvRender = new GridView();
gvRender.HeaderStyle.CssClass = "reportHeader";
gvRender.HeaderStyle.Font.Bold = true;
gvRender.HeaderStyle.BackColor = Color.FromArgb(192, 202, 227);
gvRender.AlternatingRowStyle.CssClass = "arial8pt";
gvRender.AlternatingRowStyle.BackColor = ColorTranslator.FromHtml("#BAC4DD");
gvRender.RowStyle.BackColor = Color.White;
gvRender.RowStyle.ForeColor = Color.Black;
gvRender.RowStyle.Font.Bold = true;
gvRender.BorderColor = Color.Black;
gvRender.GridLines = GridLines.Both;

gvRender.DataSource = dvExportTable;
gvRender.DataBind();

      System.IO.MemoryStream PDFDocumentStream = (System.IO.MemoryStream)new ExportToPDFLib().ExportGridViewToPDF(gvRender, TitleLabel, iColumnsCount, "A4", bLandscape);
        HttpContext.Current.Response.BinaryWrite(PDFDocumentStream.ToArray());
HttpContext.Current.Response.End();
        break;
    default: //Word or Excel report

        DataGrid dg = new DataGrid();

        dg.HeaderStyle.CssClass = "reportHeader";
        dg.HeaderStyle.Font.Bold = true;
        dg.HeaderStyle.BackColor = Color.FromArgb(192, 202, 227);

        //font-family: Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; font-variant: normal ; color: black; background-color: #BAC4DD; text-align: left
        dg.AlternatingItemStyle.CssClass = "arial8pt";

        dg.DataSource = dvExportTable;
        dg.DataBind();

        System.IO.StringWriter swRenderDataGrid = new System.IO.StringWriter();
        HtmlTextWriter hwDataGrid = new HtmlTextWriter(swRenderDataGrid);
        dg.RenderControl(hwDataGrid);

        System.IO.StringWriter swFile = new System.IO.StringWriter();
        string HostName = HttpContext.Current.Request.Url.Host;
        swFile.Write("<img height='50px' width='200px' src=http://" + HostName + HttpContext.Current.Request.ApplicationPath + "/Images/newpchlogo-modified.jpg />");
        HttpContext.Current.Response.Write(swFile.ToString() + "<BR><BR><BR><BR><FONT size=\"4\"><B>" + TitleLabel + "</B></FONT><BR>" + swRenderDataGrid.ToString() + "<BR><BR>" + "<FONT size=\"4\"><B> PCH-Portal </B></FONT><BR><FONT size=\"4\"><B> Powered By : Hovservices </B></FONT><BR><FONT size=\"4\"><B>" + DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss") + "</B></FONT><BR>");
        HttpContext.Current.Response.End();
        swRenderDataGrid.Close();
        swFile.Close();
        break;
}

}
catch (Exception ex)
{
//throw ex;
}

}
}

}

Here i cant able to give the PDF Dll. Instead of using ExportToPDFLib().ExportGridViewToPDF, we may download the shareware PDF dll and make a change and use of it. sorry for this Inconvenient code.