0 Replies - 1173 Views - Last Post: 09 May 2014 - 10:32 AM

#1 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3517
  • View blog
  • Posts: 12,008
  • Joined: 12-December 12

Find and colour text in DataGridView

Posted 09 May 2014 - 10:32 AM

This uses the DGV's CellFormatting event to search for text and apply a colour to it. Deleting the search text and performing the search again will remove the colour.

I'm using a TextBox and a Button to perform the search.
You could use a background colour instead, or both.
It searches every cell, but you could restrict it to particular columns using e.columnIndex.
    public partial class Form1 : Form {
        string searchTerm = String.Empty;
        bool searching = false;

        public Form1() {
            InitializeComponent();
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
            if (searching && e.Value != null) {
                string stringValue = (string)e.Value;
                stringValue = stringValue.ToLower();
                if ((stringValue.IndexOf(searchTerm) > -1)) {
                    e.CellStyle.ForeColor = Color.Red;
                }
            }
        }

        private void button1_Click(object sender, EventArgs e) {
            searchTerm = textBox1.Text;
            searching = !String.IsNullOrWhiteSpace(searchTerm);
            dataGridView1.Invalidate();
        }
    }

Invalidate() causes the DGV to repaint, which triggers the CellFormatting event.

This post has been edited by andrewsw: 09 May 2014 - 10:36 AM


Is This A Good Question/Topic? 0
  • +

Page 1 of 1