Click here to Skip to main content
Click here to Skip to main content

How to Create ProgressBar Column in DataGridView

, 15 Nov 2010
Rate this:
Please Sign up or sign in to vote.
An article on how to create a ProgressBar Column in DataGridView
ProgressBarColumn.jpg

Introduction

A couple of days ago, I was working on a program that allows users to upload multiple files on a server. I realized it would be nice to show progress of upload for every file individually. I tried to find a way how to solve this. After hours of “Googling” I found some solutions, how to show progress bar in DataGridView object so I decided to create my own custom progress bar column. Articles I found served as a guide for me and I have picked up same ideas, how to customize DataGridView columns. I have implemented some functionality that I will describe later.

Background

DataGridView control provides several column types, enabling users to enter and edit values in a variety of ways. Sometimes these column types do not meet needs, but that’s not a problem because you can create your own column types that can host controls you need. When you want to create your own column type, you must define some classes derived from DataGridViewColumn and DataGridViewCell.

In this short example, I will show you how to create a progress bar column. This example does not directly insert progress bar control into a cell, it only draws a rectangle which looks like a progress bar.

To do this, you must define classes that derive from DataGridViewColumn and DataGridViewImageCell. (You can also derive from DataGridViewCell which is the base type of all cells directly, but in this case is much more suitable to derive from DataGridViewImageCell, because we will use some graphical operations.)

Main Steps

As I mentioned earlier, two classes must be created. The first class I have created is DataGridViewProgressColumn which derives from DataGridViewImageColumn. This class creates a custom column for hosting progress bar cells and overrides property CellTemplate.

public class DataGridViewProgressColumn : DataGridViewImageColumn
{
        . . . 

        public override DataGridViewCell CellTemplate
        {
            get
            {
                return base.CellTemplate;
            }
            set
            {
                if (value != null &&
                    !value.GetType().IsAssignableFrom(typeof(DataGridViewProgressCell)))
                {
                    throw new InvalidCastException("Must be a DataGridViewProgressCell");
                }
                base.CellTemplate = value;
            }
        }

       . . .
}

The second class I have created is DataGridViewProgressBarCell. This class creates a custom cell for hosting a progress bar. This class derives from DataGridViewImageCell.

When developing a custom cell type, it is also critical to check if some virtual methods need to be overridden. In this example, two methods need to be overridden: Clone() method and Paint() method.

Paint() Method

In order to draw the content of the cell in the way we wanted, we must overload the paint method. This method is a critical one for any cell type. It is responsible for painting a cell. It sets various properties and is responsible for calling Graphics.FillRectangle(…) and Graphics.DrawString(…) methods which draw progress bar and write a text.

protected override void Paint(System.Drawing.Graphics g, 
    System.Drawing.Rectangle clipBounds, 
    System.Drawing.Rectangle cellBounds, 
    int rowIndex, 
    DataGridViewElementStates cellState, 
    object value, object formattedValue, 
    string errorText, 
    DataGridViewCellStyle cellStyle, 
    DataGridViewAdvancedBorderStyle advancedBorderStyle, 
    DataGridViewPaintParts paintParts)
{
    if (Convert.ToInt16(value) == 0 || value == null)
    {
        value = 0;
    }
    
    int progressVal = Convert.ToInt32(value);
    
    // Need to convert to float before division; 
    //otherwise C# returns int which is 0 for anything but 100%.
    float percentage = ((float)progressVal / 100.0f); 
    Brush backColorBrush = new SolidBrush(cellStyle.BackColor);
    Brush foreColorBrush = new SolidBrush(cellStyle.ForeColor);
    
    // Draws the cell grid
    base.Paint(g, clipBounds, cellBounds, rowIndex, 
        cellState, value, formattedValue, errorText, 
        cellStyle, advancedBorderStyle, 
	(paintParts & ~DataGridViewPaintParts.ContentForeground));
        
    float posX = cellBounds.X;
    float posY = cellBounds.Y;
    
    float textWidth = TextRenderer.MeasureText
	(progressVal.ToString() + "%", cellStyle.Font).Width;
    float textHeight = TextRenderer.MeasureText
	(progressVal.ToString() + "%", cellStyle.Font).Height;
    
    //evaluating text position according to selected alignment
    //default text alignment is TopLeft
    //variables posX and posY determine position of progress value text (percentage+"%")
    switch (cellStyle.Alignment)
    {
        case DataGridViewContentAlignment.BottomCenter:
            posX = cellBounds.X + (cellBounds.Width / 2) - textWidth / 2;
            posY = cellBounds.Y + cellBounds.Height - textHeight;
            break;
        case DataGridViewContentAlignment.BottomLeft:
            posX = cellBounds.X;
            posY = cellBounds.Y + cellBounds.Height - textHeight;
            break;
        case DataGridViewContentAlignment.BottomRight:
            posX = cellBounds.X + cellBounds.Width - textWidth;
            posY = cellBounds.Y + cellBounds.Height - textHeight;
            break;
        case DataGridViewContentAlignment.MiddleCenter:
            posX = cellBounds.X + (cellBounds.Width / 2) - textWidth / 2;
            posY = cellBounds.Y + (cellBounds.Height / 2) - textHeight / 2;
            break;
        case DataGridViewContentAlignment.MiddleLeft:
            posX = cellBounds.X;
            posY = cellBounds.Y + (cellBounds.Height / 2) - textHeight / 2;
            break;
        case DataGridViewContentAlignment.MiddleRight:
            posX = cellBounds.X + cellBounds.Width - textWidth;
            posY = cellBounds.Y + (cellBounds.Height / 2) - textHeight / 2;
            break;
        case DataGridViewContentAlignment.TopCenter:
            posX = cellBounds.X + (cellBounds.Width / 2) - textWidth / 2;
            posY = cellBounds.Y;
            break;
        case DataGridViewContentAlignment.TopLeft:
            posX = cellBounds.X;
            posY = cellBounds.Y;
            break;
            
        case DataGridViewContentAlignment.TopRight:
            posX = cellBounds.X + cellBounds.Width - textWidth;
            posY = cellBounds.Y;
            break;
    }
    
    if (percentage >= 0.0)
    {
        // Draw the progress 
        g.FillRectangle(new SolidBrush(_ProgressBarColor), cellBounds.X + 2, 
            cellBounds.Y + 2, Convert.ToInt32((percentage * cellBounds.Width * 0.8)), 
            cellBounds.Height / 1 - 5);
        //Draw text
        g.DrawString(progressVal.ToString() + "%", 
		cellStyle.Font, foreColorBrush, posX, posY);
    }
    else
    {
        //if percentage is negative, we don't want to draw progress bar
        //we want only text
        if (this.DataGridView.CurrentRow.Index == rowIndex)
        {
            g.DrawString(progressVal.ToString() + "%", cellStyle.Font, 
                new SolidBrush(cellStyle.SelectionForeColor), posX, posX);
        }
        else
        {
            g.DrawString(progressVal.ToString() + "%", cellStyle.Font, 
                foreColorBrush,posX, posY);
        }
    }
}

This method is also responsible for correct rendering of text according to alignment selected by user. This alignment can be selected in CellStyle Builder Window.

The Clone() Method

The DataGridViewImageCell derives from DataGridViewCell class that implements the ICloneable interface. Each custom cell type typically needs to override the Clone() method to copy its custom properties. Cells are cloneable because a particular cell instance can be used for multiple rows in the grid. This is the case when the cell belongs to a shared row. When a row gets unshared, its cells need to be cloned. Following is the implementation for the Clone() method:

public override object Clone()
{
    DataGridViewProgressCell dataGridViewCell = base.Clone() as DataGridViewProgressCell;
    if (dataGridViewCell != null)
    {
        dataGridViewCell.ProgressBarColor = this.ProgressBarColor;
    }
    return dataGridViewCell;
}

ProgressBarColor Property

I have created a new property called ProgressBarColor, which sets color of rendered progress bar. This property must be implemented in both classes (DataGridViewProgressBarCell and DataGridViewProgressBarColumn). In DataGridViewProgressBarColumn class, this method sets ProgressBarColor property of CellTemplate (which must be casted as DataGridViewProgressCell). ProgressBarColor value of CellTemplate is next passed into _progressBarColor variable of DataGridViewProgressBarCell class. _progressBarColor variable is used in Paint(…) method. Here is an implementation of ProgressBarColor property:

[Browsable(true)]
public Color ProgressBarColor
{
    get {
        if (this.ProgressBarCellTemplate == null)
        {
            throw new InvalidOperationException
		("Operation cannot be completed because this DataGridViewColumn 
		does not have a CellTemplate.");
        }
        return this.ProgressBarCellTemplate.ProgressBarColor;            
    }
    set {
        if (this.ProgressBarCellTemplate == null)
        {
            throw new InvalidOperationException
		("Operation cannot be completed because this DataGridViewColumn 
		does not have a CellTemplate.");
        }
        this.ProgressBarCellTemplate.ProgressBarColor = value;
        if (this.DataGridView != null)
        {
            DataGridViewRowCollection dataGridViewRows = this.DataGridView.Rows;
            int rowCount = dataGridViewRows.Count;
            for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
            {
                DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex);
                DataGridViewProgressCell dataGridViewCell = 
		dataGridViewRow.Cells[this.Index] as DataGridViewProgressCell;
                if (dataGridViewCell != null)
                {
                    dataGridViewCell.SetProgressBarColor(rowIndex, value);
                }
            }
            this.DataGridView.InvalidateColumn(this.Index);
        }
    }
}

As I mentioned earlier, when we want to pass ProgressBarColor value into CellTemplate, we must first get this CellTemplate. We can get CellTemplate from ProgressBarCellTemplate property of DataGridProgressColumn class. When we get this, we can easily set ProgressBarColor property of CellTemplate.

Using the Code

I have created a simple project called ProgressBarColumn. In this project, I have included one form named frmMain containing DataGridView with 2 columns. The first column is of DataGridViewTextBoxColumn Type and the second is DataGridViewProgressColumn type. In this project, I show you how to load data into DataGridView and how this grid renders DataGridViewProgressColumn.

History

  • 10 Oct 2010 - Original version posted

License

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

Share

About the Author

Kanasz Robert
Architect The Staffing Edge & Marwin Cassovia Soft
Slovakia Slovakia
My name is Robert Kanasz and I have been working with ASP.NET, WinForms and C# for several years.
MCSD - Web Applications
MCSE - Data Platform
MCPD - ASP.NET Developer 3.5
- Web Developer 4
MCITP - Database Administrator 2008
- Database Developer 2008
MCSA - SQL Server 2012
MCTS - .NET Framework 3.5, ASP.NET Applications
- SQL Server 2008, Database Development
- SQL Server 2008, Implementation and Maintenance
- .NET Framework 4, Data Access
- .NET Framework 4, Service Communication Applications
- .NET Framework 4, Web Applications
MS - Programming in HTML5 with JavaScript and CSS3 Specialist
 
Open source projects: DBScripter - Library for scripting SQL Server database objects
 

Please, do not forget vote

Comments and Discussions

 
GeneralRe: My Vote of 5 PinmvpKanasz Robert3-Sep-12 8:09 
QuestionExcellent - thanks! Pinmembercodeproject@zosoco.com10-Apr-12 18:15 
AnswerRe: Excellent - thanks! PinmvpKanasz Robert10-Apr-12 20:58 
GeneralMy vote of 5 Pinmembermanoj kumar choubey28-Mar-12 0:15 
GeneralRe: My vote of 5 PinmvpKanasz Robert25-Apr-12 22:56 
GeneralGot my 5 !!!! PinmemberMazen el Senih25-Mar-12 7:07 
GeneralRe: Got my 5 !!!! PinmvpKanasz Robert25-Apr-12 22:56 
GeneralGot my 5 !! PinmemberMazen el Senih25-Mar-12 7:05 
Thank you that was very useful. Thumbs Up | :thumbsup:
GeneralRe: Got my 5 !! PinmvpKanasz Robert25-Apr-12 22:56 
GeneralMy vote of 5 PinmemberClaudiobsb23-Dec-11 8:57 
AnswerRe: My vote of 5 PinmvpKanasz Robert19-Jan-12 3:09 
QuestionProgressbar backcolor PinmemberKarl_vw18-Dec-11 4:07 
AnswerRe: Progressbar backcolor PinmemberIlanF14-Jan-12 2:21 
QuestionMore styles PinmemberUjoLubo6-Dec-11 1:43 
AnswerRe: More styles PinmvpKanasz Robert19-Jan-12 3:10 
QuestionAdd property MaxValue Pinmemberjmarqesc22-Nov-11 7:24 
AnswerRe: Add property MaxValue PinmvpKanasz Robert19-Jan-12 3:11 
GeneralMy vote of 5 Pinmemberanhhtu16-Oct-11 15:27 
GeneralRe: My vote of 5 PinmemberKanasz Robert10-Nov-11 3:29 
QuestionWhy did you scale the cell paint width to 80% ? PinmemberMember 40404644-Aug-11 12:07 
AnswerRe: Why did you scale the cell paint width to 80% ? PinmemberMember 467896723-Aug-11 17:05 
GeneralMy vote of 4 PinmemberJuneZhang20-Mar-11 22:32 
GeneralRe: My vote of 4 PinmemberKanasz Robert2-May-11 3:54 
GeneralMy vote of 5 Pinmembernewest coder25-Jan-11 1:46 
GeneralRe: My vote of 5 PinmemberKanasz Robert2-May-11 3:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 15 Nov 2010
Article Copyright 2010 by Kanasz Robert
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid