Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paint only DataGridView's cell background not its content?

i need to paint only background of DataGridView cell not its Content.But while i'm doing painting it paint its content too.Please help me out.

My code goes like this.

private void Daywisegrid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == 0 )

            {
                using (Brush gridBrush = new SolidBrush(this.Daywisegrid.GridColor))
                {
                    using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
                    {
                        using (Pen gridLinePen = new Pen(gridBrush))
                        {
                            // Clear cell 
                            e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                            //Bottom line drawing
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom-1 , e.CellBounds.Right, e.CellBounds.Bottom-1);


                            e.Handled = true;
                        }
                    }
                }
            }
like image 247
Prakash Kunwar Avatar asked May 18 '11 07:05

Prakash Kunwar


1 Answers


i am not sure why you need to catch CellPainting event to change cell background color just do it like this

Daywisegrid.Rows[RowIndex].Cells[columnIndex].Style.BackColor = Color.Red;

But if you want to do it in painting try this

private void Daywisegrid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex == 0 )

            {
                using (Brush gridBrush = new SolidBrush(this.Daywisegrid.GridColor))
                {
                    using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
                    {
                        using (Pen gridLinePen = new Pen(gridBrush))
                        {
                            // Clear cell 
                            e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
                            //Bottom line drawing
                            e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom-1 , e.CellBounds.Right, e.CellBounds.Bottom-1);

                              // here you force paint of content
                             e.PaintContent( e.ClipBounds  );
                            e.Handled = true;
                        }
                    }
                }
            }
like image 86
IordanTanev Avatar answered Nov 06 '22 12:11

IordanTanev