【问题标题】:Is it possible to bind an array to DataGridView control?是否可以将数组绑定到 DataGridView 控件?
【发布时间】:2012-09-01 15:52:27
【问题描述】:

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

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

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

dataGridView1.DataSource = arrStudents;

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

【问题讨论】:

  • 与其他人写的一样,我倾向于使用BindingList<T>,以便在DataGridView 中可以看到对基础数据的更改。

标签: c# winforms binding


【解决方案1】:

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

【讨论】:

  • 你好,马克。我糊涂了。我做错了什么,为什么我的数组的内容没有显示在 DataGridView 中?
  • @phan arrStudents 的确切类型是什么,Student 是什么样的?
  • 嗯,确切的类型可以在我为这个问题选择的答案中找到:stackoverflow.com/questions/12321842/…。该解决方案中的“arrSummary”是我的 arrStudents 数组的样子。如果我可以将该问题中的 arrSummary 绑定到 DataGridView,我也会很高兴。
  • @phan 您接受的答案中的代码是匿名类型;在 c# 中没有可写属性,因此它与您问题中显示的代码不一致。我也使用匿名类型玩过这个,它仍然有效
  • 哇,我脑子里的灯泡亮了。谢谢马克!!!无意“撒谎”。我诚实地描述了我所看到的问题,但正如你所见,我对它的理解是错误的。
【解决方案2】:

这对我有用:

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> 而不是数组,因为它很可能必须增长。

你也是这样吗?

【讨论】:

  • 我已经尝试过了,但它不起作用。不过,我使用了一个 ArrayList 并填充了我派生的类的元素。这有关系吗?
  • 想通了。我在类中使用公共成员而不是属性。不过很奇怪!
  • 当用户添加新行时,这会自动将元素添加到列表中吗?
猜你喜欢
  • 2020-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
相关资源
最近更新 更多