DataGridView Control

Data Grid View Control C#

Data Grid View Control C# Sharp

 

The DataGridView control allows us to display data in tabular format using a powerful and flexible way. It is easier to define basic cell appearance and display formatting of cell values by using DataGridView control. The cell is the key to the DataGridView interaction. The DataGridViewCell base class is used to draw all cells. Each cell in the DataGridView can have its own style of text, background color, front color and font. However, typically several cells share specific characteristics of the style. The default data type is of type Object for the cell's value property.

You can use the DataGridView control to view a small amount of data read - only or scale it to display editable views of very large data sets.

Display and edit tabular data from many different types of data sources with the DataGridView control. It is simple and intuitive to bind data to DataGridView control and is often as simple as configuring the DataSource property. Specify the DataMember property to a string with the list or table to link to if we bind to a data source that contains multiple lists or Tables.

The DataGridView control supports the Windows Forms standard data binding model, thus binding on class instances described below.

  • Any IList class, including one - dimensional arrays, implemented interface.
  • Any class that uses the interface IListSource, such as the classes DataTable and DataSet.
  • Any IBindingList Interface Class, for example, BindingList class <T>.
  • All classes that implement the interface IBindingListView, such as the class BindingSource.

 

Syntax: dataGridView1.Columns[Index].Name = "Column Name";

Example:


private void SetupDataGridView()
        {
            dgvSongs.Name = "dgvSongs";
            dgvSongs.ColumnCount = 5;

            dgvSongs.Columns[0].Name = "Release Date";
            dgvSongs.Columns[1].Name = "Track";
            dgvSongs.Columns[2].Name = "Title";
            dgvSongs.Columns[3].Name = "Singer";
            dgvSongs.Columns[4].Name = "Album";
        }
private void PopulateDataGridView()
        {

            string[] row0 = { "1950", "29", "Bedu Pako Baramasa", "Anil Bisht & Kalpana Chauhan", "Maiti" };
            string[] row1 = { "2017", "6", "Nanda Bhagwati (Jaagar)", "Gajendra Rana", "Heema Maarchhayaan" }; //Artist : Jagdish Chamola, Dharmesh Sagar, Biroo Joshi  Music Label : T-Series
            string[] row2 = { "03/02/2015", "1", " Hurani Ko Dina", "Pummy Nawal (Pawitra)", "Hurani Ko Dina" };
            string[] row3 = { "2011", "7", "Thando Re Thando ", "Narendra Singh Negi", "Thando Re Thando" };
            string[] row4 = { "01/2014", "9", "Sun Ja Baat Meri Haan", "Rajendra Negi", "Sari Baand" };
            string[] row5 = { "09/03/2017", "13", "Chaita Ki Chaitwal", "Amit Saagar", "Chaita Ki Chaitwal" };
            string[] row6 = { "29/09/2018", "3", "Meri Bamani", "Hema Negi Karasi &Naveen Semwal", "Meri Bamani" };

            dgvSongs.Rows.Add(row0);
            dgvSongs.Rows.Add(row1);
            dgvSongs.Rows.Add(row2);
            dgvSongs.Rows.Add(row3);
            dgvSongs.Rows.Add(row4);
            dgvSongs.Rows.Add(row5);
            dgvSongs.Rows.Add(row6);

            dgvSongs.Columns[0].DisplayIndex = 3;
            dgvSongs.Columns[1].DisplayIndex = 4;
            dgvSongs.Columns[2].DisplayIndex = 0;
            dgvSongs.Columns[3].DisplayIndex = 1;
            dgvSongs.Columns[4].DisplayIndex = 2;
        }

 

Add row in DataGridView on button click

Example:


private void btnAddRow_Click(object sender, EventArgs e)
        {
            dgvSongs.Rows.Add();
        }

 

Delete row in DataGridView on button click, First of all we want to check selected row has count grater than 0 and selected row index not having -1.

Example:


 if (dgvSongs.SelectedRows.Count > 0 && dgvSongs.SelectedRows[0].Index !=dgvSongs.Rows.Count - 1)
            {
                dgvSongs.Rows.RemoveAt(dgvSongs.SelectedRows[0].Index);
            }

 

Here, we convert "Release Date" column values to Long date using ToLongDateString() on  CellFormatting event, for this first we check cell value is not equal to null.

Source Code:


private void dgvSongs_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e != null)
            {
                if (dgvSongs.Columns[e.ColumnIndex].Name == "Release Date")
                {
                    if (e.Value != null)
                    {
                        try
                        {
                            e.Value = DateTime.Parse(e.Value.ToString()).ToLongDateString();
                            e.FormattingApplied = true;
                        }
                        catch (FormatException)
                        {
                            Console.WriteLine("{0} is not a valid date.", e.Value.ToString());
                        }
                    }
                }
            }
        }

 

We can change DataGridView ColumnHeaders style ,color and Fonts, etc.


 //Change Column Header Back Color
 dgvSongs.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
 //Change Column Header Fore Color
 dgvSongs.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
 //Change Column Header Font Style
 dgvSongs.ColumnHeadersDefaultCellStyle.Font =new Font(dgvSongs.Font, FontStyle.Bold);
 //Change Row Size
 dgvSongs.AutoSizeRowsMode =  DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
 //Change Column Headers Border Style
 dgvSongs.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
 //Change Cell Border Style
 dgvSongs.CellBorderStyle = DataGridViewCellBorderStyle.Single;
 //Change Grid Color
 dgvSongs.GridColor = Color.Gray;

Example:

 

Complete Source Code:


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

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

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

        private void SetupDataGridView()
        {
            dgvSongs.Name = "dgvSongs";
            dgvSongs.ColumnCount = 5;
            dgvSongs.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
            dgvSongs.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            dgvSongs.ColumnHeadersDefaultCellStyle.Font =new Font(dgvSongs.Font, FontStyle.Bold);
            dgvSongs.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
            dgvSongs.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            dgvSongs.CellBorderStyle = DataGridViewCellBorderStyle.Single;
            dgvSongs.GridColor = Color.Gray;
            dgvSongs.RowHeadersVisible = false;

            dgvSongs.Columns[0].Name = "Release Date";
            dgvSongs.Columns[1].Name = "Track";
            dgvSongs.Columns[2].Name = "Title";
            dgvSongs.Columns[3].Name = "Singer";
            dgvSongs.Columns[4].Name = "Album";
            dgvSongs.Columns[4].DefaultCellStyle.Font = new Font(dgvSongs.DefaultCellStyle.Font, FontStyle.Italic);

            dgvSongs.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvSongs.MultiSelect = false;
            dgvSongs.Dock = DockStyle.Fill;

           
        }
        private void PopulateDataGridView()
        {

            string[] row0 = { "1950", "29", "Bedu Pako Baramasa", "Anil Bisht & Kalpana Chauhan", "Maiti" };
            string[] row1 = { "2017", "6", "Nanda Bhagwati (Jaagar)", "Gajendra Rana", "Heema Maarchhayaan" }; //Artist : Jagdish Chamola, Dharmesh Sagar, Biroo Joshi  Music Label : T-Series
            string[] row2 = { "03/02/2015", "1", " Hurani Ko Dina", "Pummy Nawal (Pawitra)", "Hurani Ko Dina" };
            string[] row3 = { "2011", "7", "Thando Re Thando ", "Narendra Singh Negi", "Thando Re Thando" };
            string[] row4 = { "01/2014", "9", "Sun Ja Baat Meri Haan", "Rajendra Negi", "Sari Baand" };
            string[] row5 = { "09/03/2017", "13", "Chaita Ki Chaitwal", "Amit Saagar", "Chaita Ki Chaitwal" };
            string[] row6 = { "29/09/2018", "3", "Meri Bamani", "Hema Negi Karasi &Naveen Semwal", "Meri Bamani" };

            dgvSongs.Rows.Add(row0);
            dgvSongs.Rows.Add(row1);
            dgvSongs.Rows.Add(row2);
            dgvSongs.Rows.Add(row3);
            dgvSongs.Rows.Add(row4);
            dgvSongs.Rows.Add(row5);
            dgvSongs.Rows.Add(row6);

            dgvSongs.Columns[0].DisplayIndex = 3;
            dgvSongs.Columns[1].DisplayIndex = 4;
            dgvSongs.Columns[2].DisplayIndex = 0;
            dgvSongs.Columns[3].DisplayIndex = 1;
            dgvSongs.Columns[4].DisplayIndex = 2;
        }
        private void dgvSongs_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e != null)
            {
                if (dgvSongs.Columns[e.ColumnIndex].Name == "Release Date")
                {
                    if (e.Value != null)
                    {
                        try
                        {
                            e.Value = DateTime.Parse(e.Value.ToString()).ToLongDateString();
                            e.FormattingApplied = true;
                        }
                        catch (FormatException)
                        {
                            Console.WriteLine("{0} is not a valid date.", e.Value.ToString());
                        }
                    }
                }
            }
        }

        private void btnAddRow_Click(object sender, EventArgs e)
        {
            dgvSongs.Rows.Add();
        }

        private void btnDeleteRow_Click(object sender, EventArgs e)
        {
            if (dgvSongs.SelectedRows.Count > 0 && dgvSongs.SelectedRows[0].Index !=dgvSongs.Rows.Count - 1)
            {
                dgvSongs.Rows.RemoveAt(dgvSongs.SelectedRows[0].Index);
            }
        }
    }
}

DataGridView Control Source Code

Video Tutorial