C# 是否可以将数组绑定到DataGridView控件?

C# 是否可以将数组绑定到DataGridView控件?,c#,winforms,binding,C#,Winforms,Binding,我有一个数组arrStudents,包含我学生的年龄、GPA和姓名,如下所示: arrStudents[0].Age = "8" arrStudents[0].GPA = "3.5" arrStudents[0].Name = "Bob" 我尝试将arrStudents绑定到DataGridView,如下所示: dataGridView1.DataSource = arrStudents; 但是数组的内容不会显示在控件中。我遗漏了什么吗?与Adolfo一样,我已经证实了这一点。显示的代码中没

我有一个数组arrStudents,包含我学生的年龄、GPA和姓名,如下所示:

arrStudents[0].Age = "8"
arrStudents[0].GPA = "3.5"
arrStudents[0].Name = "Bob"
我尝试将arrStudents绑定到DataGridView,如下所示:

dataGridView1.DataSource = arrStudents;

但是数组的内容不会显示在控件中。我遗漏了什么吗?

与Adolfo一样,我已经证实了这一点。显示的代码中没有错误,因此问题一定出在未显示的代码中

我猜:
年龄
等不是公共财产;它们要么是
内部
,要么是字段,即
公共整数
而不是
公共整数{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"};
我也会使用
列表
而不是数组,因为它很可能会增长

你也是这么做的吗


你好,马克。我很困惑。我做错了什么,为什么我的数组的内容没有显示在DataGridView中?@phan
arrStudents
的确切类型是什么,以及
Student
看起来像什么?好吧,确切类型可以在我为这个问题选择的答案中找到:。该解决方案中的“ARR摘要”就是我的ARR学生数组的样子。如果我能将该问题中的摘要绑定到DataGridView,我也会很高兴的。@phan您接受的答案中的代码是匿名类型;在c#中没有可写属性,因此它与问题中显示的代码不一致。我也用匿名类型玩过这个游戏,它仍然有效。哇,我脑子里的灯泡坏了。谢谢你,马克!!!没有“撒谎”的意图。我如实地描述了我所看到的问题,但正如你所看到的,我对它的理解是错误的。与其他人所写的一样,我倾向于使用
BindingList
,以便在
DataGridView
中可以看到对底层数据的更改。我尝试过这个方法,但没有效果。不过,我使用了一个ArrayList并填充了我派生的类的元素。这有关系吗?我知道了。我使用的是类的公共成员,而不是属性。不过很奇怪!当用户包含新行时,这会自动将元素添加到列表中吗?