Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

preface

In the previous article, the blogger simply created a class in this project to bind data to the DataGridView. But most of the projects are separate, so you have to use the class library, and it’s pretty easy to use the class library, but there are a few points that bloggers can avoid, hahaha

Once a day to prevent puppy love

1. Use the class library for data binding.

1.1 Open the project, right-click solution, and add a new project

1.2 The naming step is omitted. As shown in the figure, I created a Student

1.3 Write the field name and encapsulate it. The code is as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Student
{
 public   class student
    { public int id { get ; set ; } public string name { get; set; } public int age { get; set; }}}Copy the code

1.4 The class must be generated after it is written, otherwise the Datagridview may not recognize it

If your class library frame is higher than the window frame, it will not be compatible. Right click on the library and project to find the property, you will see the frame version number, and a warning will be reported in the reference ⚠

1.6 Attention:!! Writing to the data source, the code should put the definition class in a loop, each time a new memory is created to hold the value, so that the last value is not iterated

 private void button1_Click(object sender, EventArgs e)
        {
           
            List<Student.student> list = new List<Student.student>();
            for (int i=0; i<10; ++i)
            {
                
                     Student.student stu = new Student.student();
                    stu.id = i;
                    stu.name = "IC00" + i;
                    stu.age = 18;
                    list.Add(stu);
                
              }
            dataGridView1.DataSource = list;
        }
Copy the code

1.7 Effect Display

conclusion

This is the general effect. Note that if you are making a Windows application, you need to select the (.NET Framwork) suffix library, not the Windows application, you need to select the right library, after adding the reference, you need to generate the library again, DataGridView will recognize it. In the add-data function, you need to put the entity class definition in the loop, otherwise the DataGridView will iterate over the last value, and the list will hold the last value. Pro, not easy to create, like, comment, follow.