C# S1E4 : DataGridView with ActionButton

C# S1E4 : DataGridView with ActionButton



Language :
Platform :
Rating : No ratings yet.




Introduction

C# datagridview are quite powerful and customizable. They are designed to cover various day to day needs that we may want to incorporate in our projects especially when it comes to rendering of data. DataGridView allow us render data in grid or table format. They comprise DataGridViewRows and DataGridViewColumns. At the intersection of a row and a column is a DataGridviewCell object. It is these cells where we render our records.
Not only can we render text data but we can alos render images, buttons, comboboxes, checkboxes and autocompletes.
So today we want to see how to render an action button. Action button can be used to perform a given action on a given row. We use the DataGridViewButtonColumn class.
When a datagridviewbutton is clicked, we show a metro messagebox.

Questions this Examples helps answer.

  • How to render buttons in datagridview.
  • C# DataGridViewButton example.
  • C# Metro DataGridView tutorial.
  • C# DataGridView button get clicked row.

Asssumptions.

We assume that you can drag a DataGridView component in visual studio onto your winforms. Note that We used metro theme to theme our winforms. You don't have to do so. However, if you would want to install metro theme look at this link in youtube. For this project, simply extend the System.Windows.Form instead of MetroForm.

Screenshot

  • Here's the screenshot of the project.

C# DataGridViewButton
Project Structure
Project Structure

Source Code

Lets have a look at the project's source code.

Form1.csStudent.csVideo/DemoDownload
  •  Our Form1 class.
  • Derives from MetroForm. We use metroframework to theme our application.
  • Add datagridview in your winforms designer.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using MetroFramework;
using MetroFramework.Forms;
namespace Buttons_Column
{
    
    public partial class Form1 : MetroForm
    {
        private readonly DataGridViewButtonColumn btn=new DataGridViewButtonColumn();
        /*
         * - Our Constructor.
         */
        public Form1()
        {
            InitializeComponent();
            constructDataGridView();
        }
        /*
         * -Build our DataGridView.
         * -Specify number of columns, column header names
         * - Add button column
         * - Set datagridview columns to span the whole row width 
         * - Add Rows
         */
        private void constructDataGridView()
        {
            //ADD COLUMNS
            dataGridView1.ColumnCount = 5;
            dataGridView1.Columns[0].Name = "Name";
            dataGridView1.Columns[1].Name = "Course";
            dataGridView1.Columns[2].Name = "Course Type";
            dataGridView1.Columns[3].Name = "Level";
            dataGridView1.Columns[4].Name = "Stream";
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            addButtonColumn();
            dataGridView1.Columns.Add(btn);
            addRows();
            
        }
        /*
         * - Loop through our list of students and add them to datagridview.
         */
        private void addRows()
        {
            foreach (var student in getStudents())
            {
                dataGridView1.Rows.Add(student.Name, student.Course,student.CourseType, student.Level,student.Stream);
            }
        }
        /*
         * - Add button column
         */
        private void addButtonColumn()
        {
            btn.HeaderText = @"Action";
            btn.Name = "button";
            btn.Text = "Contact";
            btn.UseColumnTextForButtonValue = true;
        }
        /*
         * - Acts as our data source.
         * - Returns a List of students
         */
        private List<Student> getStudents()
        {
            List<Student> students = new List<Student>();
            Student s = new Student()
            {
                Name = "Galileo Galilei",
                Course = "Astronomical Studies",
                CourseType = "DIPLOMA",
                Level = 5,
                Stream = "NORTH"
            };
           students.Add(s);
           s = new Student()
           {
               Name = "Plato",
               Course = "Historical Studies",
               CourseType = "DIPLOMA",
               Level = 4,
               Stream = "WEST"
           };
           students.Add(s);
           s = new Student()
           {
               Name = "Yohannes Kepler",
               Course = "Planetary Sciences",
               CourseType = "DIPLOMA",
               Level = 3,
               Stream = "WEST"
           };
           students.Add(s);
           s = new Student()
           {
               Name = "Albert Einstein",
               Course = "Physics and Spacial Studies",
               CourseType = "BSC",
               Level = 6,
               Stream = "EAST"
           };
           students.Add(s);
           s = new Student()
           {
               Name = "Robert Openheimer",
               Course = "Nuclear Studies",
               CourseType = "BSC",
               Level = 6,
               Stream = "SOUTH"
           };
           students.Add(s);
           s = new Student()
           {
               Name = "Edwin Hubble",
               Course = "Astronomical Studies",
               CourseType = "DIPLOMA",
               Level = 4,
               Stream = "EAST"
           };
           students.Add(s);
           s = new Student()
           {
               Name = "Aristotle",
               Course = "Philosophy",
               CourseType = "DIPLOMA",
               Level = 4,
               Stream = "NORTH"
           };
           students.Add(s);
           s = new Student()
           {
               Name = "Freeman Dyson",
               Course = "Nuclear Studies",
               CourseType = "BSC",
               Level = 5,
               Stream = "SOUTH"
           };
           s = new Student()
           {
               Name = "Isaac Newton",
               Course = "Classical Physics",
               CourseType = "BSC",
               Level = 6,
               Stream = "NORTH"
           };
           students.Add(s);
           s = new Student()
           {
               Name = "Neils Boor",
               Course = "Physics and Quantum Physics",
               CourseType = "BSC",
               Level = 5,
               Stream = "West"
           };
           students.Add(s);
           s = new Student()
           {
               Name = "Eisenbough",
               Course = "Physics and Quantum Physics",
               CourseType = "BSC",
               Level = 6,
               Stream = "West"
           };
           students.Add(s);
            return students;
        }
        /*
         * - When datagridview cell is clicked
         */
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            Student[] students = getStudents().ToArray();
            // GET CLICKED BUTTON COLUMN AND SHOW MESSAGEBOX
            if (e.ColumnIndex == 5 && e.RowIndex < students.Length)
            {
                try
                {
                    string studentName = students[e.RowIndex].Name;
                    MetroMessageBox.Show(this, " Hello " + studentName + " , how are you doing with yoru studies.", "Student", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
            }
        }
    }
}

 

  •  Our Student.cs class.
  • Is our data object.
  • Represents a single student with properties like name,course etc.
namespace Buttons_Column
{
    class Student
    {
        public string Name { get; set; }
        public string Course { get; set; }
        public string CourseType { get; set; }
        public int Level { get; set; }
        public string Stream { get; set; }
    }
}
Below is the video tutorial for this project:

C# S1E4 : DataGridView with ActionButton and OnClick

  • Download the full project below:

coming soon.

How To Run

  1. Download the source code above.
  2. Extract it.
  3. In your Visual Studio: File -> Open ->Project/Solution.
  4. Choose the Solution location.
  5. Open
  6. That's it, you've imported the project to your visual studio.

OR

  1. Drag Drop a datagridview in your Form in visual studio.
  2. Copy the Form1 class above into your Form1.
  3. Also create the Student.cs class and copy code above and paste into it.

More

YouTube

  • Visit our channel for more examples like these.

Facebook

Oclemy,Cheers.



Rating :

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    5 + seven =

    COMMENTS