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

时间:2012-09-07 18:37:31

标签: c# winforms binding

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

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

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

dataGridView1.DataSource = arrStudents;

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

2 个答案:

答案 0 :(得分:9)

这对我有用:

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<Student>代替数组,因为它最有可能增长。

那也是你在做什么?

enter image description here

答案 1 :(得分:8)

与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();
        }
    }
}