C# DataGridView - ReadOnly DataGridViewCheckBoxColumn - Fill From Dictionary


C# DataGridViewCheckBoxColumn Tutorial.

How to populate a Datagridview with checkboxes with data from a dictionary. We also mark those checkboxes as readonly meaning the user cannot modify them at runtime.

Demo

Here's the demo:

C# DataGridView CheckBoxes

Video Tutorial

What You Learn in this Tutorial

(a). How to show CheckBoxes in DataGridView

Well we use the DataGridViewCheckBoxColumn to host DataGridViewCheckBoxCell objects. The DataGridViewCheckBoxColumn will then be rendered as the second column in our two-column datagridview.

Here's how we instantiate the DataGridViewCheckBoxColumn:

        DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();

Then here;s how we set it's column header:

            checkBoxColumn.Name = "ACTIVE STAR FORMATION?";

And finally here's how we add the CheckBox Column to our datagridview:

            myDataGridView.Columns.Add(checkBoxColumn);

(b). How to get the selected CheckBox Value in DataGridView

We will be having a datagridview with checkboxes. And we want to show the value of a checkbox that is selected in a messagebox. That means we have to convert that boolean value to a string.

But first we have to listen to datagridview cell click events. That means we will set our datagridview selection mode property to CellSelect"

            myDataGridView = new DataGridView
            {
                ...
                SelectionMode = DataGridViewSelectionMode.CellSelect,
                ...
            };

Then listen to create an event handler to handle the cellclick events:

        static void myDataGridView_CellClick(object sender, DataGridViewCellEventArgs e){
            ...
        }

We will have to register that event handler to our CellClick event:

            myDataGridView.CellClick += myDataGridView_CellClick;

Then we can get the cheeckbox value:

            string nebularState = myDataGridView.Rows[e.RowIndex].Cells[1].Value.ToString();

Why Show CheckBoxes in DataGridViewCells?

Well showing checkboxes in cells within the datagridview is important as it allows us easily render boolean values in datagridview. This is more intuitive than using TextBoxes as checkboxes directly correspond to the two states renderable by checkbox.

Moreover checkboxes occupy smaller spaces than textviews. They are also easily readable as the user doesn't have to read texts but can infer at a glance the value represented.

What is a DataGridViewCheckBoxColumn?

DataGridViewCheckBoxColumn is a class defined in the System.Windows.Forms class that is responsible for hosting a collection of System.Windows.Forms.DataGridViewCheckBoxCellobjects.

Basically it is the class that shows our checkboxes in columns within our datagridview. The checkboxes themselves are rendered by the DataGridViewCheckBoxCell objects.

Program.cs

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace DataGridViewCheckBoxesDictionary
{
    static class Program
    {
        private static DataGridView myDataGridView;
        private static readonly DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();

        /*
         * Setup GridView. Intantiate it, set its properties and attach an event listener
         */
        private static void setupDataGridView()
        {
            myDataGridView = new DataGridView
            {
                Location = new Point(30, 70),
                Size = new Size(500, 400),
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                SelectionMode = DataGridViewSelectionMode.CellSelect,
                ReadOnly = true,
                ColumnCount = 1
            };
            myDataGridView.Columns[0].Name = "NAME";
            checkBoxColumn.Name = "ACTIVE STAR FORMATION?";

            myDataGridView.Columns.Add(checkBoxColumn);

            populateData();
            myDataGridView.CellClick += myDataGridView_CellClick;
        }
        /*
         * When you Click a Cell, we get the selected cell contents and show in messagebox
         */
        static void myDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;

            string selectedNebular = myDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString();
            string nebularState = myDataGridView.Rows[e.RowIndex].Cells[1].Value.ToString();

            switch (e.ColumnIndex)
            {
                case 0:
                    MessageBox.Show(selectedNebular, "Nebular", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case 1:
                    MessageBox.Show(nebularState, "Nebular", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
            }
        }
        /*
         * Generate data and bind to our datagridview
         */
        private static void populateData()
        {
            Dictionary<String, Boolean> nebulae = new Dictionary<String, Boolean>
            {
                { "Horse Head",true},
                {"Black Widow",false},
                { "Ghost Head",true},
                { "Witch Head" ,false},
                { "Cat's Eye",false},
                { "Elephant's Trunk",false},
                { "Helix", false},
                { "Rosette",false},
                { "Ant",true},
                { "Orion",true},
                { "Eagle",true},
                { "Bernad 68",false},
                { "Butterfly",true},
                { "Snake",false},
                { "Own",true},
                { "Ring", true},
                { "Pelican",false},
                { "Cone",true},
                { "Flame",true},
                { "Bumerang", false}

            };
            foreach (KeyValuePair<string, bool> nebular in nebulae)
            {
                myDataGridView.Rows.Add(nebular.Key, nebular.Value);
            }
        }
        /*
         * Create a Form, Set its properties and run the application.
         */
        private static void createForm()
        {
            Form myForm = new Form
            {
                Text = "C# WinForms : DataGridView - Fill From Dictionary - Camposha.info",
                ClientSize = new Size(564, 520),
                BackColor = Color.Coral
            };

            myForm.Controls.Add(myDataGridView);
            Application.EnableVisualStyles();
            Application.Run(myForm);
        }
        /*
         * Our main method
         */
        public static void Main()
        {
            setupDataGridView();
            createForm();
        }
    }
}

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post