How to bind DataGridView to List <T> or BindingList <T>

I've done this a thousand times and it works, but now ... no :(

Am I doing something wrong here because nothing is showing in the grid?

namespace theGridIsNotWorking
{
using System;
using System.Collections.Generic;
using System.Windows.Forms;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var items = new List<Item>();

        items.Add(new Item(){ TheName = "first"});
        items.Add(new Item(){ TheName = "Second"});
        items.Add(new Item(){ TheName = "Third"});

        dataGridView1.DataSource = new List<Item>(items);
    }

    public class Item
    {
        public string TheName;
    }
}
}

      

Nothing special .... but very sad.

0


a source to share


3 answers


I think the problem is that TheName is a member variable, but you need a property. Try the following for the Item class:




      public class Item
      {
         public string TheName;

         public string TheNameProperty
         {
            get
            {
               return TheName;
            }
         }

         public Item(string name)
         {
            TheName = name;
         }
      }

      

+3


a source


Try BindingListView . Easiest way to bind List <T> to DGV.



+2


a source


BindingList<Notification>(notifications);

      

must not be

BindingList<Notification>(activeNotifications);

      

?

+1


a source







All Articles