您的位置:首页 - 教程 - WinForm - 正文
DataGridView和List<T>绑定不显示问题
源码:http://hovertree.com/h/bjaf/1x1yn77e.htm

在学习DataGridView 和List<T>绑定时发现DataGridView不会显示数据。后来发现要用类的属性才能正常显示,如果直接用类的字段等来显示,则无法显示数据。

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        private void Form1_Load(object sender, EventArgs e)
        {
           
            dgv_message.GridColor = Color.Blue;           
            dgv_message.DataSource = new List<student>()
            {
                new student(){sName="柯乐义",Age=20},
                new student(){sName="孙悟空",Age=40},
                new student(){sName="刘德华",Age=60},
                new student(){sName="何问起",Age=22}
            };
                           
               dgv_message.Columns[0].HeaderText = "姓名";
               dgv_message.Columns[1].HeaderText = "年龄";
            
        }
    }
    public class student
    {
       private string name;
       private  int age;

        public string sName
       {
           get { return name; }
           set { name = value; }
       }

        public int Age
        {
            get { return age; }
            set { age =value ; }
        }
    }
}

如果把student中类变成以下代码,则无法显示:

    public class student
    {
       public string sName;
       public int Age;      
    }

评论:
  • 2016-11-08 15:15 就你说到点子上了