C# DataGridView - With CheckBoxes


Making a custom DataGridView with CheckBoxes and handle their events.

For the CheckBox column we shall be using DataGridViewCheckBoxColumn class.We also see how to find the current position of the checkbox and check it. Here's the code.  

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CheckBox_Column
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            update();
        }

        //UPDATE DATAGRIDVIEW
        public void update()
        {
            //ADD COLUMNS
            dataGridView1.ColumnCount = 3;
            dataGridView1.Columns[0].Name = "Position";
            dataGridView1.Columns[1].Name = "Team";
            dataGridView1.Columns[2].Name = "Points";

            //ADD ROWS
            ArrayList row = new ArrayList();
            row.Add("1");
            row.Add("PSG");
            row.Add("78");
            dataGridView1.Rows.Add(row.ToArray());

            //2ND ROW
            row = new ArrayList();
            row.Add("2");
            row.Add("LYON");
            row.Add("72");
            dataGridView1.Rows.Add(row.ToArray());

            //3RD ROW
            row = new ArrayList();
            row.Add("3");
            row.Add("Marseille");
            row.Add("70");
            dataGridView1.Rows.Add(row.ToArray());

            //ADD CHECKBOX COLUMN
            DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
            chk.HeaderText = "Qualified";
            chk.Name = "CheckBox";
            dataGridView1.Columns.Add(chk);

        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.ColumnIndex==3)
            {
                MessageBox.Show((e.RowIndex+1).ToString()+" Row Clicked");

            }
        }
    }
}

Cheers.

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