Thứ Năm, 10 tháng 9, 2009

Search Records In GridView And Highlight Results Using AJAX ASP.NET

In this example i am searching records of gridview and highlighting the results based on search criteria user enter in textbox .



This example is using AJAX and C# asp.NET





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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Grid Search example</title>
<style type="text/css">
.highlight {
text-decoration:none; font-weight:bold;
color:black; background:yellow;}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"
runat="server" />

<div>
Enter first name to search:
</div>
<div>
<asp:TextBox ID="txtSearch" runat="server"
AutoPostBack="True"
OnTextChanged="txtSearch_TextChanged">
</asp:TextBox>&nbsp;
</div>
<div>
<asp:UpdatePanel ID="UpdatePanel1"
runat="server">
<ContentTemplate>
<asp:GridView ID="grdSearch"
runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName"
runat="server"
Text='<%# Highlight(Eval("FirstName").ToString()) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server"
Text='<%#(Eval("LastName")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server"
Text='<%#(Eval("Location")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch"
EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>

</div>

</form>
</body>
</html>


And it code behind

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

public partial class _Default : System.Web.UI.Page
{
string strConnection =
ConfigurationManager.AppSettings["ConnectionString"];
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}

private DataTable GetRecords()
{
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Employees";
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
return objDs.Tables[0];

}
private void BindGrid()
{
DataTable dt = GetRecords();
if (dt.Rows.Count > 0)
{
grdSearch.DataSource = dt;
grdSearch.DataBind();
}
}
private void SearchText()
{
DataTable dt = GetRecords();
DataView dv = new DataView(dt);
string SearchExpression = null;
if (!String.IsNullOrEmpty(txtSearch.Text))
{
SearchExpression = string.Format("{0} '%{1}%'",
grdSearch.SortExpression, txtSearch.Text);

}
dv.RowFilter = "FirstName like" + SearchExpression;
grdSearch.DataSource = dv;
grdSearch.DataBind();

}
public string Highlight(string InputTxt)
{
string Search_Str = txtSearch.Text.ToString();
// Setup the regular expression and add the Or operator.
Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(),
RegexOptions.IgnoreCase);

// Highlight keywords by calling the
//delegate each time a keyword is found.
return RegExp.Replace(InputTxt,
new MatchEvaluator(ReplaceKeyWords));

// Set the RegExp to null.
RegExp = null;

}

public string ReplaceKeyWords(Match m)
{

return "<span class=highlight>" + m.Value + "</span>";

}

protected void txtSearch_TextChanged(object sender, EventArgs e)
{
SearchText();
}
}




Download the sample code







Related Posts:

1. Search within records in GridView with searchbox in footer and highlight results using AJAX and C# ASP.NET

2. User validation across pages using session after login in ASP.NET using C sharp

3. Finding IP address behind Proxy using C# in ASP.NET

Thứ Tư, 9 tháng 9, 2009

SubReports in Crystal Reports in ASP.NET

In this example i am going to describe how to create SubReports in Crystal Reports in ASP.NET.

For this i have used two tables from MS SQL database named Employees and Projects.
Main Crystal Report is fetching data from both the tables and is grouped by Project Name

SubReport is used to display information about respective project and fetching data from Projects Table.

Schema for both the tables in shown below in images, create tables accordingly and add relevant data in it to start.

You can click on Images to Enlarge



To start , Create a new website in VS and right click on Solution Explorer and select Add new Item > Crystal Report. In the wizard window choose Using the Report Wizard radio button and Standard type in Choose an Expert section.


In next screen select Expand OLEDB(ADO) and Choose create new connection


Select Microsoft OLEDB Provider for SQL server and click next


In next screen check the Integrated security checkbox so that report doesn't ask for username and password Enter you SQL Server name and Select DataBase from the dropdown ,


In next window expand and locate your tables you want to use and add them in right pane



In next screen select the fields you want to display in main report and add them in right pane , in my case i am showing fields from two tables in main report
Now select the field which you want report to be grouped by ( in this example i m grouping report by Project Name)

Select the report style you want and finish the wizard

Now to add a subReport Right click in group header section (below Group #1 Name)
Choose Insert > SubReport , Place the ractangle where you want SubReport to be displayed. a wizard window will open prompltly


Enter report Name and click on report wizard buttonin next screen ,



Choose the table and fields you want to use in SubReport in next two screens and click on finish
Now Insert subReport window will open again , In this window click on Link Tab and select the field on which you want to filter SubReport or the ID of the record to show SubReport. I am using ProjectID in this example.

This is how design of report will look like


And this is how report preview will look


Save , build and rum the website.
Now if you don't want to show SubReport but want to put a hyperlink instead or want to create On-Demand SubReport then do these changes in the design of report
Right click on SubReport in Design View and select Format Object


In the window opened ,Go to SubReport tab, Change the SubReport name to text you want to show as hyperlink, Check the On-demand SubReport check box and click on ok


Now design of report will look like image below



On default.aspx page drag CrystalReportViewer from toolbox and assign CrystalReport we just created as source
Html source will go like this (AutoGenerated)

AutoDataBind="True" Height="1039px"
ReportSourceID="CrystalReportSource1"
Width="901px" />






Save, build and run the solution , this is how report will look like

Hope this helps

Crystal Reports in ASP.NET

In this example i m going to describe how to create crystal reports in ASP.NET.

In this i am generating report by fetching data from two tables and grouping them based on Project Name. Database tables are just for demo purpose you can create your own tables with whatever schema you want
Two tables are as shown below.


Create a new website and right click on solution explorer > add new Item > Select Crystal Report
In the dialog box choose blank report.

Now click on CrystalReports Menu in VS and select DataBase Expert
In database expert dialog box expend create new connection > OLEDB(ADO) section
Now select SQL Native client and enter you SQL server address , username , password and pick database name from the dropdown.
In next screen Expend your database objects in left pane and add the tables you want to use in right pane
Link your tables based on Primary keys (If any)

Click ok to finish the wizard.
Right click on Field Explorer and select Group Name Fields > Insert Group

In next box select the field you to report to be grouped (in my case it's ProjectsName)

Click on OK to finish
Now design the report , drag and fields from Database fields in field explorer and which you want to show in report and drop them in Section3(Details), and preview the report, it should look like show below.


Go to default.aspx page and drag and drop CrystalReportViewer from the toolbox, click on smart tag and choose new report source.
Choose you report from the dropdown menu and click ok to finish.
Now when you build and run the sample , it asks for the database password everytime.

To fix this we need to load the report programmatically and provide username and password from code behind .
Now run the report , it should look like this


Html markup of default.aspx look like
<form id="form1" runat="server">

<div>
<CR:CrystalReportViewer ID="CrystalReportViewer1"
runat="server" AutoDataBind="True"
Height="1039px"
ReportSourceID="CrystalReportSource1"
Width="901px" />
<CR:CrystalReportSource ID="CrystalReportSource1"
runat="server">
<Report FileName="CrystalReport.rpt">
Report>
CR:CrystalReportSource>

div>
form>

C# code behind

Write this code in the event you find appropriate , i m writing it in Page_Load , you can write this code in click event of button or in pagePreRender event
The code to provide password programmatically.
protected void Page_Load(object sender, EventArgs e)

{
ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("CrystalReport.rpt"));
crystalReport.SetDatabaseLogon
("amit", "password", @"AMIT\SQLEXPRESS", "TestDB");
CrystalReportViewer1.ReportSource = crystalReport;
}

VB.NET code behind
Protected Sub Page_Load

(ByVal sender As Object, ByVal e As EventArgs)

Dim crystalReport As New ReportDocument()

crystalReport.Load(Server.MapPath("CrystalReport.rpt"))

crystalReport.SetDatabaseLogon
("amit", "password", "AMIT\SQLEXPRESS", "TestDB")

CrystalReportViewer1.ReportSource = crystalReport

End Sub

Hope this helps