Click here to Skip to main content
6,595,854 members and growing! (17,716 online)
Email Password   helpLost your password?
Desktop Development » Grid & Data Controls » DataGrid and DataView     Intermediate License: The zlib/libpng License

Cell Blink for DataGridView

By Raghavan Ram Raja

An article on adding a cell blink feature for DataGridView
C# 2.0, Windows, .NET 2.0, Visual Studio, WinForms, Dev
Posted:7 Sep 2007
Updated:4 May 2008
Views:45,418
Bookmarked:81 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
14 votes for this article.
Popularity: 4.91 Rating: 4.29 out of 5

1

2
3 votes, 21.4%
3
4 votes, 28.6%
4
7 votes, 50.0%
5
Screenshot - DataGridViewCellBlink.jpg

Introduction

After reading many articles on The Code Project, I realized that it's my time to contribute. Few months ago, I came across a requirement for cells in a DataGridView control to blink when the cell value changed. The code presented here can be applied to any other grid.

The blinking of the grid cell is achieved in the following manner. When we update the value of a cell, we also change the background color of that cell to a blink color. To restore the cell background color to its original value, we run a background thread that iterates through a list of cells that are blinking and resets them to their original non blinking state.

The Code

The sample project has two functions. The first function DataInputThreadFunc() is used to generate random values to be filled / updated in the grid. The second function GridBlinkThreadFunc() is used to restore the cells to the non blink state.

Let's take a look at the first function DataInputThreadFunc():

private void DataInputThreadFunc()
{
    Random rand = new Random();
    while (true)
    {
        if (dataGridView1.IsDisposed)
            break;

        CellData data = new CellData();
        data.Row = rand.Next(0, 7);
        data.Col = rand.Next(0, 3);
        data.Time = DateTime.Now;

        int value = rand.Next(0, 101);

        dataGridView1.Invoke((MethodInvoker)delegate()
        {
            dataGridView1.Rows[data.Row].Cells[data.Col].Value = value;
            dataGridView1.Rows[data.Row].Cells[data.Col].Style
              .BackColor = Color.Salmon;
        });

        lock (_blinkData)
        {
            _blinkData.Add(data);
        }

        Thread.Sleep(1000);
    }
}

The function uses a while (true) loop as it's a background thread and will be shutdown automatically when the application is closed. if (dataGridView1.IsDisposed) check is done to make sure we do not call dataGridView1.Invoke() on a disposed object. This can happen when the user closes the application.

Next, we initialize an object of the class CellData to store the blink data:

class CellData
{
     public int Row;
     public int Col;
     public DateTime Time;
}

This class is used to store the row number, column number and the time when the value changed.

Next we use dataGridView1.Invoke() to make a call to the user interface thread and set the grid properties. We save the blink data in a generic list to be used later by the blink thread function. Since the list is altered by more than one thread, we synchronize access by locking the list on each access.

Now let's take a look at the blink thread function:

private void GridBlinkThreadFunc()
{
    while (true)
    {
        // Make a copy to avoid invalid operation exception
        // while iterating through the map
        List<CellData> tempBlinkData;
        lock (_blinkData)
        {
            tempBlinkData = new List<CellData>(_blinkData);
        }

        foreach (CellData data in tempBlinkData)
        {
            TimeSpan elapsed = DateTime.Now - data.Time;
            if (elapsed.TotalMilliseconds > 500) // 500 is the Blink delay
            {
                if (dataGridView1.IsDisposed)
                    return;

                dataGridView1.BeginInvoke((MethodInvoker)delegate()
                {
                    dataGridView1.Rows[data.Row].Cells[data.Col]
                      .Style.BackColor = dataGridView1.Columns[data.Col]
                      .DefaultCellStyle.BackColor;
                });

                lock (_blinkData)
                {
                    _blinkData.Remove(data);
                }
            }
        }

        Thread.Sleep(250); // Blink frequency
    }
}

At the very beginning, we make a copy of the _blinkData list. This helps us to modify the list while we iterate through the contents of the temporary copy. For each cell we find in the list, we check to make sure whether the blink time has elapsed or not. In this case, the blink time is 500 milliseconds. Any cell that has elapsed the blink time gets its background color reset to the default cell style background color and is removed from the list.

Again we make sure that we set the grid property only in the user interface thread. In addition, we lock the _blinkData list before altering it. Thread.Sleep(250) is the frequency with which we go through the list to turn off the cells. Ideally, it should be half the value of blink delay.

Points of Interest

You will notice that this code can be applied to any grid. This code can also be hidden in a class that extends a DataGridView control.

One thing I love about .NET 2.0 is dataGridView1.Invoke((MethodInvoker)delegate(). This statement lets you get away from writing a function and declaring a delegate.

A good point was made by "Kristof Verbiest" about the use of BeginInvoke() instead of Invoke(). The GridBlinkThreadFunc() uses BeginInvoke() to avoid unnecessary context switch.

History

  • 09/06/2007: First published
  • 09/11/2007: Changed the GridBlinkThreadFunc() to use BeginInvoke() instead of Invoke()
  • 05/02/2008: Edited the "Points of Interest" section

License

This article, along with any associated source code and files, is licensed under The zlib/libpng License

About the Author

Raghavan Ram Raja


Member
Nothing to brag about! Just another passionate software developer!Smile

Work to make a living, don't live to work!
Occupation: Software Developer (Senior)
Location: United States United States

Other popular Grid & Data Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 16 of 16 (Total in Forum: 16) (Refresh)FirstPrevNext
GeneralPerformance issue PinmemberHoa Le16:19 10 Nov '08  
GeneralRe: Performance issue PinmemberRaghavan Ram Raja4:21 14 Nov '08  
GeneralRe: Performance issue PinmemberHoa Le18:27 20 Nov '08  
GeneralVB.NET Version Here (Visual Studio 2005) Pinmembergratro3:26 14 Oct '08  
GeneralRe: VB.NET Version Here (Visual Studio 2005) PinmemberRaghavan Ram Raja4:07 14 Oct '08  
GeneralBlink PinmembertxALI5:16 29 Jan '08  
GeneralSome comments PinmemberKristof Verbiest21:16 10 Sep '07  
GeneralRe: Some comments PinmemberRam Mohan Raja5:42 11 Sep '07  
GeneralRe: Some comments PinmemberKristof Verbiest22:11 11 Sep '07  
GeneralRe: Some comments PinmemberRam Mohan Raja5:46 12 Sep '07  
GeneralRe: Some comments PinmemberKristof Verbiest22:06 12 Sep '07  
GeneralRe: Some comments PinmemberRam Mohan Raja5:05 13 Sep '07  
GeneralRe: Some comments PinmemberKristof Verbiest5:40 13 Sep '07  
GeneralRe: Some comments [modified] PinmemberRam Mohan Raja6:40 13 Sep '07  
GeneralRe: Some comments Pinmemberradioman.lt@gmail.com1:26 31 Oct '07  
GeneralRe: Some comments PinmemberRam Mohan Raja4:33 31 Oct '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 4 May 2008
Editor: Deeksha Shenoy
Copyright 2007 by Raghavan Ram Raja
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project