.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month

Home >> Code Snippets >> DataGrid >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Gridview Search word with highlight using c#

Posted By:Lalij Mer       Posted Date: May 14, 2010    Points: 10    Category: DataGrid    URL: http://www.dotnetspark.com  

Search any word or string from gridview with highlight.

  • -> Create a Gridview with TemplateFields for the fields for search.
  • -> Create a datasource with a FilterExpression.
  • -> Add a Search Box.
  • -> at last add the CSS class for highlighting.
using System.Text.RegularExpressions;

partial class GridviewwithHighlightedSearch : System.Web.UI.Page

	// Create a String to store our search results

	string SearchString = "";
	public string HighlightText(string InputTxt)
		// This function is called whenever text is displayed in the FirstName and LastName 
		// fields from our database. If we're not searching then just return the original 
		// input, this speeds things up a bit
		if (string.IsNullOrEmpty(SearchString)) {
			return InputTxt;
		} else {
			// Otherwise create a new regular expression and evaluate the FirstName and 
			// LastName fields against our search string.
			Regex ResultStr = default(Regex);
			ResultStr = new Regex(SearchString.Replace(" ", "|"), RegexOptions.IgnoreCase);
			return ResultStr.Replace(InputTxt, new MatchEvaluator(ReplaceWords));

	public string ReplaceWords(Match m)
		// This match evaluator returns the found string and adds it a CSS class I defined 
		// as 'highlight'
		return "" + m.ToString + "";

	protected void btnClear_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		// Simple clean up text to return the Gridview to it's default state
		txtSearch.Text = "";
		SearchString = "";

	protected void btnSearch_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		// Set the value of the SearchString so it gets 
		SearchString = txtSearch.Text;


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend