Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - Is it possible to bind an array to DataGridView control?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...