Highlight Search Text In Data Grid View cell

In this section, we will see how the search text is highlighted in the Data Grid View cell where it has matched. We will apply searching over selected columns of the grid.

Example

Suppose we have a search textbox and Data Grid View which is displaying the data.

Task

Whatever text we will write over the search text box, this text needs to search over the Data Grid View over specific columns and highlight the matched words over the grid cell with yellow color.

Controls used

Data Grid View and a text box.

Columns participate in searching

Name, Address, and Notes.

Events used

txtSearch_KeyUp - for getting the text for searching.

dataGridViewForSearching_CellPainting - it is used to highlight the search text in the Data Grid View cell.

frmHighlightSearchTextInDataGridView_Load- form load event to bind the grid.

ASP.NET 

How it works

In the below screen, let's type “at” over search text box and it highlights the data over the grid.

ASP.NET 

Steps involve in highlighting the search text over grid cell -

Step 1

Add “data grid view” and “text box” control in the form.

Step 2

Create data table to bind with the Data Grid View.

  1. public frmHighlightSearchTextInDataGridView() {  
  2.     InitializeComponent();  
  3. }  
  4. publicDataTable GetTable() {  
  5.     // Here we create a DataTable with four columns.  
  6.     DataTable table = newDataTable();  
  7.     table.Columns.Add("Id"typeof(int));  
  8.     table.Columns.Add("Name"typeof(string));  
  9.     table.Columns.Add("Address"typeof(string));  
  10.     table.Columns.Add("Notes"typeof(string));  
  11.     // Here we add 5 DataRows.  
  12.     table.Rows.Add(2, "Pankaj""Greater Noida UP""Shared folder");  
  13.     table.Rows.Add(3, "Manoj""Pauri Garhwal UK""Asp.net framework");  
  14.     table.Rows.Add(4, "DigVijay""Gorakhpur UP""MVC views");  
  15.     table.Rows.Add(5, "Sumit""Bareilly UP""creating object");  
  16.     table.Rows.Add(6, "Varun""NCR""App_Data ");  
  17.     return table;  
  18. }  

Step 3

Bind theData Grid View with table on the form load event.

  1. privatevoid frmHighlightSearchTextInDataGridView_Load(object sender, EventArgs e) {  
  2.     // Bind the DataGridView  
  3.     dataGridViewForSearching.DataSource = GetTable();  
Step 4

Create function SearchDataInDataGridViewOverSelectedFields() for filter or search the searching text into data table which are used to bind the Data Grid View.

  1. privateDataTable SearchDataInDataGridViewOverSelectedFields(String searchText, DataTable dt) {  
  2.     DataView dvForSearch = newDataView(dt);  
  3.     // Apply search over selective fields.  
  4.     dvForSearch.RowFilter = "Name Like '%" + searchText + "%' or Address Like '%" + searchText + "%' or Notes Like '%" + searchText + "%'";  
  5.     return dvForSearch.ToTable();  
  6. }  
In the above function, we used RowFilter to filter the data from data table by applying over selective fields.

Step 5

Use txtSearch_KeyUp event to get the searching text as input from user.

  1. privatevoid txtSearch_KeyUp(object sender, KeyEventArgs e) {  
  2.     DataTable dt = GetTable();  
  3.     if (!String.IsNullOrWhiteSpace(txtSearch.Text.Trim())) {  
  4.         DataTable dtAfterSerach = SearchDataInDataGridViewOverSelectedFields(txtSearch.Text.Trim(), dt);  
  5.         dataGridViewForSearching.DataSource = dtAfterSerach;  
  6.     } else {  
  7.         dataGridViewForSearching.DataSource = dt;  
  8.     }  
  9. }  
Now, so far, if we run the application, it will filter the data of the data grid on the basis of search textbox data, but it will not highlight the matched text. So, for achieving this highlighted cell content, we will use cellPainting event ofData Grid View.

 Step 5

Use dataGridViewForSearching_CellPainting() for paint the match text in grid cell with the background yellow color.

  1. privatevoid dataGridViewForSearching_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {  
  2.     // High light and searching apply over selective fields of grid.  
  3.     if (e.RowIndex > -1 && e.ColumnIndex > -1 && dataGridViewForSearching.Columns[e.ColumnIndex].Name != "Id") {  
  4.         // Check data for search  
  5.         if (!String.IsNullOrWhiteSpace(txtSearch.Text.Trim())) {  
  6.             String gridCellValue = e.FormattedValue.ToString();  
  7.             // check the index of search text into grid cell.  
  8.             int startIndexInCellValue = gridCellValue.ToLower().IndexOf(txtSearch.Text.Trim().ToLower());  
  9.             // IF search text is exists inside grid cell then startIndexInCellValue value will be greater then 0 or equal to 0  
  10.             if (startIndexInCellValue >= 0) {  
  11.                 e.Handled = true;  
  12.                 e.PaintBackground(e.CellBounds, true);  
  13.                 //the highlite rectangle  
  14.                 Rectangle hl_rect = newRectangle();  
  15.                 hl_rect.Y = e.CellBounds.Y + 2;  
  16.                 hl_rect.Height = e.CellBounds.Height - 5;  
  17.                 //find the size of the text before the search word in grid cell data.  
  18.                 String sBeforeSearchword = gridCellValue.Substring(0, startIndexInCellValue);  
  19.                 //size of the search word in the grid cell data  
  20.                 String sSearchWord = gridCellValue.Substring(startIndexInCellValue, txtSearch.Text.Trim().Length);  
  21.                 Size s1 = TextRenderer.MeasureText(e.Graphics, sBeforeSearchword, e.CellStyle.Font, e.CellBounds.Size);  
  22.                 Size s2 = TextRenderer.MeasureText(e.Graphics, sSearchWord, e.CellStyle.Font, e.CellBounds.Size);  
  23.                 if (s1.Width > 5) {  
  24.                     hl_rect.X = e.CellBounds.X + s1.Width - 5;  
  25.                     hl_rect.Width = s2.Width - 6;  
  26.                 } else {  
  27.                     hl_rect.X = e.CellBounds.X + 2;  
  28.                     hl_rect.Width = s2.Width - 6;  
  29.                 }  
  30.                 //color for showing highlighted text in grid cell  
  31.                 SolidBrush hl_brush;  
  32.                 hl_brush = newSolidBrush(Color.Yellow);  
  33.                 //paint the background behind the search word  
  34.                 e.Graphics.FillRectangle(hl_brush, hl_rect);  
  35.                 hl_brush.Dispose();  
  36.                 e.PaintContent(e.CellBounds);  
  37.             }  
  38.         }  
  39.     }