是否可以绑定一个数组来DataGridView控件? [英] Is it possible to bind an array to DataGridView control?
问题描述
我有一个数组,arrStudents,包含我的学生的年龄,GPA和名称,像这样:
I have an array, arrStudents, that contains my students' age, GPA, and name like so:
arrStudents[0].Age = "8"
arrStudents[0].GPA = "3.5"
arrStudents[0].Name = "Bob"
我试图arrStudents绑定到像这样一个DataGridView:
I tried to bind arrStudents to a DataGridView like so:
dataGridView1.DataSource = arrStudents;
但是,数组的内容不会在控制出现。我缺少的东西吗?
But the contents of the array do NOT show up in the control. Am I missing something?
推荐答案
与阿道夫,我已经验证了这个的和的。没有什么错在code显示的是,所以这个问题必须在code你没有显示。
As with Adolfo, I've verified that this works. There is nothing wrong in the code shown, so the problem must be in the code you aren't showing.
我的猜测:年龄
等不公开的属性;他们要么是内部
或它们的字段的,即公众诠释年龄;
而不是公众诠释年龄{获取;集;}
My guess: Age
etc are not public properties; either they are internal
or they are fields, i.e. public int Age;
instead of public int Age {get;set;}
.
这是你的code为一个良好的类型数组和匿名类型的数组工作:
Here's your code working for both a well-typed array and an array of anonymous types:
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();
}
}
}
这篇关于是否可以绑定一个数组来DataGridView控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!