none
Highlight Text in DatagridView

    Question

  • I have been able to highlight selected text within a cell of the datagridview control, but I have a column where the text wraps and it does not highlight the search text properly. If I do not have the column word wrap set it all works fine.

    Any one shine some light on this for me.

     

      public static void HighlightTextInDataGridView(string searchText, int columnIndex, DataGridViewCellPaintingEventArgs e)
        {
          if (searchText == string.Empty || e.ColumnIndex == -1 || e.RowIndex == -1)
          {
            return;
          }
          else
          {
            int characterIndex = -1;
            string cellText = Convert.ToString(e.FormattedValue);
            characterIndex = cellText.IndexOf(searchText, StringComparison.OrdinalIgnoreCase);
            if (cellText == string.Empty || characterIndex == -1)
            {
              return;
            }
            else
            {
              if (columnIndex != -1)
              {
                if (columnIndex != e.ColumnIndex)
                {
                  return;
                }
              }
              // handle the paint event manually
              e.Handled = true;
    
              // get a list of charcater ranges
              List<CharacterRange> ranges = new List<CharacterRange>();
              while (!(characterIndex == -1))
              {
                ranges.Add(new CharacterRange(characterIndex, searchText.Length));
                characterIndex = cellText.IndexOf(searchText, characterIndex + searchText.Length, StringComparison.OrdinalIgnoreCase);
              }
    
              // string formats
              StringFormat stringFormat = StringFormat.GenericDefault;
              stringFormat.FormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.MeasureTrailingSpaces;
              stringFormat.Trimming = StringTrimming.None;
              stringFormat = GetCellAlignmentValues(stringFormat, e);
              stringFormat.SetMeasurableCharacterRanges(ranges.ToArray());
              // decode the alignment values from cells to string format alignments
              
    
              // check if the cell is selected
              bool selected = (e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected;
              // paint the background of the cell
              e.PaintBackground(e.ClipBounds, selected);
    
              // get the regions for the search text
              Region[] stringRegions = e.Graphics.MeasureCharacterRanges(cellText, e.CellStyle.Font, e.CellBounds, stringFormat);
    
              // loop through the regions highlighting the text
              foreach (Region highlight in stringRegions)
              {
                if (selected == true)
                {
                  // selected
                  e.Graphics.FillRegion(Brushes.DarkBlue, highlight);
                }
                else
                {
                  // not selected
                  e.Graphics.FillRegion(Brushes.CornflowerBlue, highlight);
                }
    
                // clean up
                highlight.Dispose();
              }
    
              stringFormat.Dispose();
              e.PaintContent(e.ClipBounds);
              e.Paint(e.ClipBounds, DataGridViewPaintParts.Border);
            }
          }
        }

     

     

    Monday, October 18, 2010 8:00 AM

Answers

  • Hi FrustratedMan,

     

    I think that you should check the rule of search. Please check the following information, might help.

     

    E.G. StringFormat.LineLimit “Only entire lines are laid out in the formatting rectangle. By default layout continues until the end of the text, or until no more lines are visible as a result of clipping, whichever comes first. Note that the default settings allow the last line to be partially obscured by a formatting rectangle that is not a whole multiple of the line height. To ensure that only whole lines are seen, specify this value and be careful to provide a formatting rectangle at least as tall as the height of one line.”

     

    MeasureTrailingSpaces “Includes the trailing space at the end of each line. By default the boundary rectangle returned by the MeasureString method excludes the space at the end of each line. Set this flag to include that space in measurement.”

     

    See: http://msdn.microsoft.com/en-us/library/system.drawing.stringformatflags.aspx for more information.

     

    CHEERS,

    Larcolais


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Thursday, October 21, 2010 9:21 AM

All replies

  • Hi FrustratedMan,

     

    Thank you for your post.

     

    By default, text in a DataGridViewTextBoxCell does not wrap. This can be controlled via the WrapMode property on the cell style (e.g. DataGridView.DefaultCellStyle.WrapMode). Set the WrapMode property of a DataGridViewCellStyle to one of the DataGridViewTriState enumeration values.

     

    The following code example uses the DataGridView.DefaultCellStyle property to set the wrap mode for the entire control.

     

    this.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

     

    CHEERS,

    Larcolais


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Wednesday, October 20, 2010 7:23 AM
  • Hi Larcolais,

    Thanks for the reply, the issue is not the wrapping but the highlighting of the text.

    I have a search function where if the user enters a partial text say "abc" it will search through all the cells in the grid and highlight matching "abc" in each string of text (eg "time to say abc") in this case the abc would be highlighted. This all works fine for grid cells where the wrapping is set to false. Its when I have a column with wrapping set to true and the text wraps onto several lines that the hightlight does not work properly, it highlights something other than the "abc"

     

     

     

     

    Wednesday, October 20, 2010 10:11 AM
  • Hi FrustratedMan,

     

    I think that you should check the rule of search. Please check the following information, might help.

     

    E.G. StringFormat.LineLimit “Only entire lines are laid out in the formatting rectangle. By default layout continues until the end of the text, or until no more lines are visible as a result of clipping, whichever comes first. Note that the default settings allow the last line to be partially obscured by a formatting rectangle that is not a whole multiple of the line height. To ensure that only whole lines are seen, specify this value and be careful to provide a formatting rectangle at least as tall as the height of one line.”

     

    MeasureTrailingSpaces “Includes the trailing space at the end of each line. By default the boundary rectangle returned by the MeasureString method excludes the space at the end of each line. Set this flag to include that space in measurement.”

     

    See: http://msdn.microsoft.com/en-us/library/system.drawing.stringformatflags.aspx for more information.

     

    CHEERS,

    Larcolais


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Thursday, October 21, 2010 9:21 AM