Wednesday, June 1, 2011

How to highlight a DataGridView row or make it glow temporarily?

Simulate the user selecting a row, use

myDataGrid.Rows[n].IsSelected = true;

In order to temporarily color highlight a row in a DataGridView control, set the DefaultCellStyle.BackColor property to a color of your choice for the row you are interested in. Then enable a System.Windows.Forms.Timer control for the time period of your choice. When the timer's Tick event fires, disable the timer and set the row's DefaultCellStyle.BackColor back to its original color.

The short example below is for a WinForm application that has a DataGridView named GlowDataGrid, a timer named GlowTimer, and a button named GlowButton. When clicking on GlowButton, the third row of the DataGridView glows yellow temporarily for two seconds.

private void Form1_Load(object sender, EventArgs e)
// initialize datagrid with some values
string[] names = new string[] { "Mary","James","Michael","Linda","Susan"};
for(int i = 0; i < 5; i++)
GlowDataGrid[0, i].Value = names[i];
GlowDataGrid[1, i].Value = i;

private void GlowButton_Click(object sender, EventArgs e)
// set third row's back color to yellow
GlowDataGrid.Rows[2].DefaultCellStyle.BackColor = Color.Yellow;
// set glow interval to 2000 milliseconds
GlowTimer.Interval = 2000;
GlowTimer.Enabled = true;

private void GlowTimer_Tick(object sender, EventArgs e)
// disable timer and set the color back to white
GlowTimer.Enabled = false;
GlowDataGrid.Rows[2].DefaultCellStyle.BackColor = Color.White;

Handling using timer for Highlighting row.

No comments:

Post a Comment