C# DataGridView - With CheckBoxes

July 4, 2017 Oclemy C# DataGridView, C# Button 0 minutes, 59 seconds

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.

Comments