Display Records from Database using CrystalReportViewer

In this blog we will discuss how to display records from a database using CrystalReportViewer. 

Default.aspx code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ReportViewer._Default" %>

<%@ Register assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" namespace="CrystalDecisions.Web" tagprefix="CR" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">
   
<title>Untitled Page</title>

/head>

<body>
   
<form id="form1" runat="server">

   
<div>

   
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"

       
AutoDataBind="true" />

   
</div>

   
</form>

</
body>
</
html> 

Default.aspx.cs code

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;
using
System.Data.SqlClient;
using
CrystalDecisions.CrystalReports.Engine;

namespace ReportViewer


{

   
public partial class _Default : System.Web.UI.Page

   
{

       
string connStr =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

       
SqlDataAdapter sqlda = new SqlDataAdapter();

       
SqlCommand com = new SqlCommand();

       
DataTable dt;

       
DataSet1 ds=new DataSet1();

       
ReportDocument rptDoc=new ReportDocument();
 
       
protected void Page_Load(object sender, EventArgs e)

       
{

           
bindReport();
 
       
}

       
private void bindReport()

       
{
           
           
SqlConnection conn = new SqlConnection(connStr);

           
dt = new DataTable();

           
dt.TableName = "Crystal Report Example";

           
com.Connection = conn;

           
com.CommandText = "SELECT * FROM product";

           
sqlda = new SqlDataAdapter(com);

           
sqlda.Fill(dt);

           
ds.Tables[0].Merge(dt);

           
rptDoc.Load(Server.MapPath("CrystalReport1.rpt"));

           
rptDoc.SetDataSource(ds);

           
CrystalReportViewer1.ReportSource = rptDoc;
 
       
}

   
}

Ebook Download
View all
Learn
View all