C# S1E5 : DataGridView MasterDetail CRUD with Forms

C# S1E5 : DataGridView MasterDetail CRUD with Forms



Language :
Platform :
Rating : 5/5 (1)




Introduction

We are continuing with our C# series. Previously we looked at how to render action buttons in a datagridview component. We also saw how to handle the button clicks wehere we saw how to show a messagebox. In this example we look at how to render multiple action buttons in the datagridview and make a master detail example with multiple forms.
The point is that the user can perform basic CRUD: add edit update and delete data to and from our datagridview. The new action button when clicked opens a form for adding new data/or registering a student. The edit action button opens a form for editing the student details. The delete action button delete's the student.
Now for simplicity we are using a simple static data holder class to temporarily hold our data.

Questions this Examples helps answer.

  • How to render multiple action buttons in datagridview.
  • C# Master Detail datagridview example.
  • C# DataGridView master detail forms CRUD example.
  • C# Metro DataGridView add update delete 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.

 

Project Structure
Project Structure

Source Code

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

Student.csDataHolder.csDataEntry.csForm1.csVideo/DemoDownload
  • Our Student class.
  • Is our data object.
  • Represents a single student with properties like id,name and course.
using System;
namespace MasterDetail_ActionButtons
{
    
    public class Student
    {
        public int Id { get; set; }
        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; }
        public DateTime DOB { get; set; }
        public string Hostel { get; set; }
    }
}

 

  • Is our DataHolder class.
  • Contains a List which acts as our data source.
  • We initial the list with initial data.
using System;
using System.Collections.Generic;
namespace MasterDetail_ActionButtons
{
   
    class DataHolder
    {
        public static List<Student> students=new List<Student>();
        /*
         * - Return list of students
         */
        public static List<Student> getStudents()
        {
            if (students.Count > 0)
            {
                return students;
            }
            
            Student initialStudent = new Student
            {
                Id = students.Count,
                Name = "Albert Einstein",
                CourseType = "BSC",
                Course = "Physics and Quantum Mechanics",
                Level = 6,
                Stream = "EAST",
                Hostel = "Whirlpool",
                DOB = DateTime.Now
                
            };
            students.Add(initialStudent);
            return students;
        }
    }
}

 

  • Our DataEntry class.
  • Derives from MetroForm hence will display a UI.
  • Used for either registering student or updated existing student.
  • Acts as our detail form.
using System;
using System.Collections.Generic;
namespace MasterDetail_ActionButtons
{
    
    class DataHolder
    {
        public static List<Student> students=new List<Student>();
        /*
         * - Return list of students
         */
        public static List<Student> getStudents()
        {
            if (students.Count > 0)
            {
                return students;
            }
            
            Student initialStudent = new Student
            {
                Id = students.Count,
                Name = "Albert Einstein",
                CourseType = "BSC",
                Course = "Physics and Quantum Mechanics",
                Level = 6,
                Stream = "EAST",
                Hostel = "Whirlpool",
                DOB = DateTime.Now
                
            };
            students.Add(initialStudent);
            return students;
        }
    }
}

 

  • Our Form1 class.
  • Extends MetroForm hence will show a metro-themed UI.
  • Is our master form.
  • Will contain datagridview with data and action buttons.
using System;
using System.Windows.Forms;
using MetroFramework.Forms;
namespace MasterDetail_ActionButtons
{
    
    public partial class Form1 : MetroForm
    {
        /*
         * - Constructor.
         */
        public Form1()
        {
            InitializeComponent();
            this.constructDataGridView();
        }
        /*
         * - Setup datagridview columns.
         * - Add button columns as well.
         * - 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("New");
            addButtonColumn("Edit");
            addButtonColumn("Refresh");
            addButtonColumn("Delete");
            addRows();
        }
        /*
         * - Loop through students and add them to datagridview.
         */
        private void addRows()
        {
            dataGridView1.Rows.Clear();
            foreach (var student in DataHolder.getStudents())
            {
                dataGridView1.Rows.Add(student.Name, student.Course, student.CourseType, student.Level, student.Stream);
            }
        }
        /*
         * - How to Add button column.
         */
        private void addButtonColumn(string btnText)
        {
            ////ADD BUTTON COLUMN
            DataGridViewButtonColumn btn = new DataGridViewButtonColumn
            {
                HeaderText = btnText.ToUpper(),
                Name = btnText,
                Text = btnText,
                UseColumnTextForButtonValue = true
            };
            dataGridView1.Columns.Add(btn);
        }
        /*
         * - DataGridView cells clicked.
         */
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // New button is clicked.
            if (e.ColumnIndex == 5 && e.RowIndex < DataHolder.students.Count)
            {
                try
                {
                    //Show form for registering new student.
                    DataEntry dataEntry=new DataEntry(null);
                    dataEntry.Show();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
            }
                //Edit button is clicked.
            else if (e.ColumnIndex == 6 && e.RowIndex < DataHolder.students.Count)
            {
                try
                {
                    //Show Form for editing existing student.
                    int id = e.RowIndex;
                    Student studentToEdit = DataHolder.students.ToArray()[id];
                    DataEntry dataEntry=new DataEntry(studentToEdit);
                    dataEntry.Show();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
            }
                //Refresh button is clicked.
            else if (e.ColumnIndex == 7 && e.RowIndex < DataHolder.students.Count)
            {
                try
                {
                    //Refresh datagridview to show updated data.
                    addRows();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
            }
                //Remove button is clicked.
            else if (e.ColumnIndex == 8 && e.RowIndex < DataHolder.students.Count)
            {
                try
                {
                    //remove student.
                    int id = e.RowIndex;
                    DataHolder.students.RemoveAt(id);
                    addRows();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
            }
        }
    }
}

 

Below is the video tutorial for this project.

C# S1E5 : DataGridView - MasterDetail CRUD with Forms

  • Download the full project below: Comming soon.
Download

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.cs, DataEntry.cs,Student.cs and DataHolder.cs class above and modify the namespaces to suit your project name.

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 × five =

    COMMENTS