How to create datagridview custom column

How to create custom column for datagridview using C#

DataGridView found on .netframework 2.0 is to display tabular date on your application. DataGridView support following types of columns

1. DataGridViewTextBoxColumn

2. DataGridViewButtonColumn

3. DataGridViewCheckBoxColumn

4. DataGridViewComboBoxColumn

5. DataGridViewImageColumn

6. DataGridViewLinkColumn

In this walkthrough we are creating new type of custom Column to support our own needs. If your purpose is not fullfilled by any one of the above column types you can create your own type. 

 

Create custom column

I wanted to create a custom column to dynamically show colored stripe based on row value. Depending on the status of the row the column will have different colored stripe. For eg: If row is new -> Blue and row is approved-> green etc. 

Creating custom column is simple, create a class named "DatagirdViewStripeCell"  and  inherit it from DataGridViewTextBoxCell. Override the paint event of this class to suit your needs. In this example we draw a colored strip. Create another class "DatagridViewStripeColumn" inherting from DataGridViewColumn. 

After you compile the project while adding column on your gridview you can see your new column type along with builtin columns. See image below. 

 

Code for custom striped column

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

namespace testproject
{
    public sealed class DatagridViewStripeColumn : DataGridViewColumn
    {
        public DatagridViewStripeColumn()
        {
            CellTemplate =
            new DatagirdViewStripeCell();
            ReadOnly = true;

        }
    }
    public class DatagirdViewStripeCell : DataGridViewTextBoxCell
    {

        protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);

            var cellValue = (string)value;
            const int vertoffset = 0;
            const int horizontaloffset = 0;
            var newRect = new Rectangle(
               cellBounds.X + horizontaloffset,
               cellBounds.Y + cellBounds.Height - 10,
               cellBounds.Width,
               8);
            graphics.FillRectangle(new SolidBrush(GetColor(cellValue)), newRect);
        }
        void DrawString(Graphics graphics, Rectangle cellBounds, DataGridViewElementStates cellState, string cellText)
        {
            Font fnt = new Font("Arial", 12, GraphicsUnit.Pixel);

            SizeF textSize =
               graphics.MeasureString(cellText, fnt);


            //  Calculate the correct color:
            Color textColor = Color.Black;
            if ((cellState &
               DataGridViewElementStates.Selected) ==
               DataGridViewElementStates.Selected)
            {
                textColor = InheritedStyle.SelectionForeColor;
            }
            // Draw the text:
            using (SolidBrush brush =
            new SolidBrush(textColor))
            {
                graphics.DrawString(cellText, fnt, brush,
                  cellBounds.X,
                  cellBounds.Y);
            }
        }


        private static Color GetColor(string data)
        {
            if (data == "new")
            {
                //Blue
                return Color.FromArgb(51, 153, 255);
            }
            else if (data == "forward")
            {
                //Yellow
                return Color.FromArgb(255, 204, 102);
            }
            else if (data == "rejected")
            {
                //Red
                return Color.FromArgb(255, 51, 0);
            }
            else if (data == "approved")
            {
                //Green
                return Color.FromArgb(0, 204, 0);
            }
            return Color.White;
        }
    }
}
 

The custom column "DataGridViewStipeColumn" show on dropdown while addin column on datagridview.

Bind the data to grid and test

		 dataGridView1.AutoGenerateColumns = false;
            IList<Mydata> list = new List<Mydata>(){
                new Mydata(){Title="tile 1 ",Status="new"},
               new Mydata(){Title="tile 2 ",Status="approved"},
               new Mydata(){Title="tile 3 ",Status="rejected"},
               new Mydata(){Title="tile 4 ",Status="forward"},
               new Mydata(){Title="tile 5 ",Status="new"},
               new Mydata(){Title="tile 6 ",Status="approved"},
               
            };
            mydataBindingSource.DataSource= list;
 


Result

Here is the datagridview with custom column rendered.


Like us

See also

Websockets using Node.js on openshfit platform

Node.js is getting popular these days. Node.js is best for developing realtime web applications like multiplayer games, real time chat applications. This will guide you how you can use node.js to create a simple chat application. And we will also hos...