Can I associate an array with a DataGridView control?

I have an array, arrStudents, which contains the age of my students, GPA, and the name like this:

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

I tried to associate arrStudents with a DataGridView as follows:

 dataGridView1.DataSource = arrStudents; 

But the contents of the array are NOT displayed in the control. Did I miss something?

+4
source share
2 answers

Like Adolfo, I confirmed that it works. There is nothing wrong with the code shown, so the problem should be in code that you are not showing.

My guess: Age , etc. are not publicly available; either they are internal , or they are fields, i.e. public int Age; instead of public int Age {get;set;} .

Here, your code works 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(); } } } 
+7
source

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 would also use List<Student> instead of an array, since it should have grown most likely.

Is that what you do too?

enter image description here

+9
source

Source: https://habr.com/ru/post/1433023/


All Articles