8

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

arrStudents[0].Age = "8"
arrStudents[0].GPA = "3.5"
arrStudents[0].Name = "Bob"

我试图将 arrStudents 绑定到 DataGridView,如下所示:

dataGridView1.DataSource = arrStudents;

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

4

2 回答 2

10

与 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();
        }
    }
}
于 2012-09-07T18:40:39.767 回答
10

这对我有用:

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"};

我也会使用 aList<Student>而不是数组,因为它很可能必须增长。

这也是你在做的吗?

在此处输入图像描述

于 2012-09-07T18:44:55.080 回答