Is it possible to bind an array to DataGridView control?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-30 09:27:52

问题


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"

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?


回答1:


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

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



回答2:


This works for me:

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

Or less redundant:

arrStudents[0] = new Student {Age = 8, GPA = 3.5, Name = "Bob"};

I'd also use a List<Student> instead of an array since it will have to grow most likely.

Is That what you're doing too?



来源:https://stackoverflow.com/questions/12323596/is-it-possible-to-bind-an-array-to-datagridview-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!