是否可以将数组绑定到DataGridView控件?
我有一个数组arrStudents,其中包含我的学生的年龄,GPA和姓名,如下所示:
arrStudents[0].Age = "8" arrStudents[0].GPA = "3.5" arrStudents[0].Name = "Bob"
我试图将arrStudents绑定到DataGridView,如下所示:
dataGridView1.DataSource = arrStudents;
但是数组的内容不会出现在控件中。 我错过了什么吗?
和Adolfo一样,我已经证实这是有效的 。 显示的代码没有任何问题,因此问题必须出在您未显示的代码中。
我的猜测: Age
等不是公共财产; 要么它们是internal
要么是字段 ,即public int Age;
而不是public int Age {get;set;}
。
这是您的代码适用于类型良好的数组和匿名类型数组:
using System; using System.Linq; using System.Windows.Forms; public class Student { public int Age { get; set; } public double GPA { get; set; } public string Name { get; set; } } internal class Program { [STAThread] public static void Main() { Application.EnableVisualStyles(); using(var grid = new DataGridView { Dock = DockStyle.Fill}) using(var form = new Form { Controls = {grid}}) { // typed var arrStudents = new[] { new Student{ Age = 1, GPA = 2, Name = "abc"}, new Student{ Age = 3, GPA = 4, Name = "def"}, new Student{ Age = 5, GPA = 6, Name = "ghi"}, }; form.Text = "Typed Array"; grid.DataSource = arrStudents; form.ShowDialog(); // anon-type var anonTypeArr = arrStudents.Select( x => new {x.Age, x.GPA, x.Name}).ToArray(); grid.DataSource = anonTypeArr; form.Text = "Anonymous Type Array"; form.ShowDialog(); } } }
这对我有用:
public class Student { public int Age { get; set; } public double GPA { get; set; } public string Name { get; set; } } public Form1() { InitializeComponent(); Student[] arrStudents = new Student[1]; arrStudents[0] = new Student(); arrStudents[0].Age = 8; arrStudents[0].GPA = 3.5; arrStudents[0].Name = "Bob"; dataGridView1.DataSource = arrStudents; }
或者更少冗余:
arrStudents[0] = new Student {Age = 8, GPA = 3.5, Name = "Bob"};
我还使用List
而不是数组,因为它最有可能增长。
这就是你在做什么吗?