Click here to Skip to main content
6,631,889 members and growing! (21,090 online)
Email Password   helpLost your password?
Desktop Development » Grid & Data Controls » Grid controls     Beginner License: The Code Project Open License (CPOL)

Use Event to Set Row/Cell BackColor in Custom DataGridView

By HU Lihui

Introduces an event method to set row/cell BackColor in custom DataGridView
C# 2.0.NET 2.0VS2005, Dev, Design
Posted:19 Sep 2008
Views:13,346
Bookmarked:19 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
5 votes for this article.
Popularity: 2.68 Rating: 3.83 out of 5

1
1 vote, 20.0%
2

3
1 vote, 20.0%
4
3 votes, 60.0%
5

CustomDataGridView

Figure 1: BackColor of Cell[1,1](RowIndex = 1, ColIndex =1) 

Figure 2: BackColor of Row 2(RowIndex = 2, ColIndex = -1)

Introduction

If we want to set row or cell backcolor in our custom DataGridView control, we may have many methods, such as customizing column, using DefaultCellStyle, etc..Here a method by way of .NET event will be introduced. 

The realized steps include: define CellBackColorEventArgs class, customize DataGridView control with SetCellBackColor event, override OnCellPainting method, draw cell BackColor if the event has been subscribed. 

1) Define an EventArgs Class

    public class CellBackColorEventArgs : EventArgs
    {
        private int m_RowIndex;
        private int m_ColIndex;
        private Color m_BackColor = Color.Empty;
  
        public CellBackColorEventArgs(int row, int col)
        {
            m_RowIndex = row;
            m_ColIndex = col;
        }

        public int RowIndex
        { 
            get { return m_RowIndex; } 
        }
        
        public int ColIndex
        { 
            get { return m_ColIndex; } 
        }
        
        public Color BackColor
        {
            get { return m_BackColor; }
            set { m_BackColor = value; }
        }
    }

The CellBackColorEventArgs class has two public readonly properties: RowIndex and ColIndex, which use to denote current cell in OnCellPainting event of DataGridView. The public property BackColor has default value Color.Empty denoting no BackColor to be assigned to this cell.

2) Customize a DataGridView Control

    public class CustomDataGridView : DataGridView
    {
        public CustomDataGridView() { }

        [Description("Set cell background color, Colindex -1 denotes any col.")]
        public event EventHandler<CellBackColorEventArgs> SetCellBackColor;

        private void DrawCellBackColor(DataGridViewCellPaintingEventArgs e)
        {
            if ((e.State & DataGridViewElementStates.Selected) == 
					DataGridViewElementStates.Selected)
            {
                base.OnCellPainting(e);
                return;
            }

            if (this.SetCellBackColor == null)  // this event has no subscriber
            {
                base.OnCellPainting(e);
                return;
            }

            CellBackColorEventArgs ee = new CellBackColorEventArgs
					(e.RowIndex, e.ColumnIndex);
            this.SetCellBackColor(this, ee);  //  get the EventArgs ee

            if (ee.BackColor == Color.Empty)  // if subscriber does not set BackColor
            {
                base.OnCellPainting(e);
                return;
            }

            using (SolidBrush fillBrush = new SolidBrush(ee.BackColor))
            using (Pen gridPenColor = new Pen(this.GridColor))
            {
                Rectangle rect1 =  
			new Rectangle(e.CellBounds.Location, e.CellBounds.Size);
                Rectangle rect2 = 
			new Rectangle(e.CellBounds.Location, e.CellBounds.Size);
                
                rect1.X -= 1;
                rect1.Y -= 1;

                rect2.Width -= 1;
                rect2.Height -= 1;

	       // must draw border for grid scrolling horizontally 
                e.Graphics.DrawRectangle(gridPenColor, rect1);  

                e.Graphics.FillRectangle(fillBrush, rect2);
            }

            e.PaintContent(e.CellBounds);  // output cell text
            e.Handled = true;
        }

        protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)  // data cell
            {
                this.DrawCellBackColor(e);
            }
            else
            {
                base.OnCellPainting(e);
            }
        }
    }

The code above has three contents: 

  • public event EventHandler<CellBackColorEventArgs> SetCellBackColor defines an event using generic delegate EventHandler<T>
  • DrawCellBackColor method is used to draw one cell
  • Overrides OnCellPainting and uses DrawCellBackColor when current is data cell, that is e.RowIndex >=0 and e.ColIndex >= 0 

Key skills

The first skill is to capture the event SetCellBackColor before drawing cell, and judges if it has subcription.If the event has been subscribed, then tests the return parameter ee(see code below),and if ee.BackColor is not Color.Empty which denoting BackColor is assigned to current cell, draws the cell including border, background color and content.

 if (this.SetCellBackColor == null)  // this event has no subscriber
 {
    base.OnCellPainting(e);
    return;
  }

  CellBackColorEventArgs ee = new CellBackColorEventArgs(e.RowIndex, e.ColumnIndex);
  this.SetCellBackColor(this, ee);  //  get the eventArgs

  if (ee.BackColor == Color.Empty)  // if subscriber does not set BackColor
  {
     base.OnCellPainting(e);
     return;
  }  

Another skill is that we can set row or cell  by one Event. If we give -1 to col index that we want to change BackColor, we will set the whole row BackColor as usage example below.

Using the code  

After unzipping the CustomDataGridView.zip, we can click doubly the solution file CustomDataGridView.sln to view the test project if we have Visual Studio 2005/2008, or we can run file CustomDataGridView.exe in folder \bin to test the control.

The windows application can see example code below:    

  private void customDataGridView1_SetCellBackColor
		(object sender, CellBackColorEventArgs e)
  {
     if (e.RowIndex != (int)nu_RowIndex.Value)  // not current row
     {
        return;
     }
            
     if((int)nu_ColIndex.Value == -1)  // denote any col, i.e. the whole row
     {
        e.BackColor = Color.LightCoral;
     }
     else if ((int)nu_ColIndex.Value == e.ColIndex)  // only current cell
     {
        e.BackColor = Color.LightCoral;
     }
  }

  private void nu_RowIndex_ValueChanged(object sender, EventArgs e)
  {
      customDataGridView1.Refresh();
  }
  private void nu_ColIndex_ValueChanged(object sender, EventArgs e)
  {
      customDataGridView1.Refresh();
  }	

The objects nu_RowIndex and nu_ColIndex are NumericUpDown controls, and nu_RowIndex.Value is the row index we want to change BackColor, nu_ColIndex.Value is the col index.

Three Usage Notes 

  • The row index what we want to change BackColor must be the same as CellBackColorEventArgs e.RowIndex  
  • We can set the whole row BackColor if the col index is -1 and the row index is equal to e.RowIndex
  • We will set the cell BackColor if col index and row index are same as e.ColIndex and e.RowIndex each other. 

Conclusion

We can set row or cell BackColor in our custom DataGridView control by way of .NET event, and we find this method can be applied to many other cased  such as merging cells, setting assigned cell to be readonly, etc..

You can view the Chinese contents that I wrote at http://download.csdn.net/source/612515. (only demo and no source code).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

HU Lihui


Member
College teacher and free programmer who expertises application sofwares for statistics reports,finance data handling,and MIS using Visual C#, Delphi, SQL, etc..
Occupation: Instructor / Trainer
Company: CSUST
Location: China China

Other popular Grid & Data Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
  (Refresh) 
-- There are no messages in this forum --

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

PermaLink | Privacy | Terms of Use
Last Updated: 19 Sep 2008
Editor: Deeksha Shenoy
Copyright 2008 by HU Lihui
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project