4
Answers

DataGridView Row painting (DefaultCellStyle.BackColor)

Sam

Sam

11y
3.6k
1
Hi,
I have a DataGridView who's datasource is a datatable.
I try to paint certain rows by changing the BackColor.

I can easily change the background color of columns, but to modify the row backcolor, I must run the datagrid twice. 
Here is a test program I made, with datatable and datagridview;
When first run, the Column[1] is painted, the row does not.
Only when clicking the button (re-running the DataGridView) the row is being painted.
The same problem is experienced in my larger, main program.
Can anyone suggest how to overcome the problem?
(I could naturally run the grid twice, but this does not seem to be an acceptable solution) 

using System.Data;
using System.Drawing;
using System.Windows.Forms;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            buildTable();
            buildGrid();
        }


        int row;
        DataTable table = new DataTable();
 
        public void buildTable()
        {
            table.TableName = "table";
            table.Columns.Add("0", typeof(int));
            table.Columns.Add("1", typeof(int));
            table.Columns.Add("2", typeof(int));
            for (row = 0; row < 10; row++)
            {
                table.Rows.Add(row, 1, 2);
            }
        }


        public void buildGrid()
        {
            dataGridView1.DataSource = table;
            dataGridView1.Columns[1].DefaultCellStyle.BackColor = Color.LightGreen;
            dataGridView1.Rows[1].DefaultCellStyle.BackColor = Color.LightGreen;
        }


        private void button1_Click(object sender, System.EventArgs e)
        {
            buildGrid();
        }
    }
}




Answers (4)