DataGridView和List<T>绑定不显示问题
在学习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; }