Changing row color in not-active DataGridView
What's the best way of changing some rows back color in DataGridView, when it's not active??
In "real" world I would like to use it for formatting all DataGridView rows after button click, depending on some criterias.
To reproduce behaviour, please try:
1. In WinForms application put TabControl with 开发者_运维技巧two tab pages. On the first tab put button, on second - DataGridView. 2. Use following code:using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public int counter = 0;
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Surname", typeof(string));
dt.Rows.Add("Mark", "Spencer");
dt.Rows.Add("Mike", "Burke");
dt.Rows.Add("Louis", "Amstrong");
dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
counter++;
this.Text = "Event counter: " + counter.ToString();
dataGridView1.Rows[1].DefaultCellStyle.BackColor = System.Drawing.Color.Red;
}
}
}
I put the counter variable for testing different options to see, how many times the event of color changing is fired (less is better ;) - ideally only once).
Now, when you first click the button WITHOUT going on tabPage2, and then you switch to tabPage2 - the color of row will not change. This is the problem I have.
It will work when you first activate tabPage2, and then press the button, or when you programatically set tabControl1.SelectedIndex = 1;
, then color row and then switch back to tabControl1.SelectedIndex = 0;
- but in this situation it "blinks".
I also tried to put code of color changing to cell_painting event, but for me it's overkill - it's fired couple hundred times in short time, even when you move mouse over datagridview, while I need to do it only once.
Do you have any advice how to solve that issue?
Best regards,
MarcinOne possibility is to the colour within the datagridview paint event (which gets fired when the tabpage changes).
private void dataGridView1_Paint(object sender, PaintEventArgs e)
{
dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
}
This works nicely for me - the paint event does get called several times when you change the tab, so if you want to only set the DefaultCellStyle once you could do something like:
public partial class Form1 : Form
{
private bool setcol;
private bool painted;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
setcol = true;
painted = false;
}
private void dataGridView1_Paint(object sender, PaintEventArgs e)
{
if (setcol && !painted)
{
painted = true;
dataGridView1.Rows[0].DefaultCellStyle.BackColor = Color.Red;
}
}
}
精彩评论