pha*_*han 6 c# binding winforms
我有一个数组arrStudents,其中包含我的学生的年龄,GPA和姓名,如下所示:
arrStudents[0].Age = "8"
arrStudents[0].GPA = "3.5"
arrStudents[0].Name = "Bob"
Run Code Online (Sandbox Code Playgroud)
我试图将arrStudents绑定到DataGridView,如下所示:
dataGridView1.DataSource = arrStudents;
Run Code Online (Sandbox Code Playgroud)
但是数组的内容不会出现在控件中.我错过了什么吗?
Ado*_*rez 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;
}
Run Code Online (Sandbox Code Playgroud)
或者更少冗余:
arrStudents[0] = new Student {Age = 8, GPA = 3.5, Name = "Bob"};
Run Code Online (Sandbox Code Playgroud)
我也会使用a List<Student>而不是数组,因为它最有可能增长.
这就是你在做什么吗?

和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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33897 次 |
| 最近记录: |