c# - 无法从列表中的 DataGridView 中加载数据

标签 c# winforms datagridview

我试图在 Windows 窗体应用程序的 DataGridView 中显示数据库中的数据,但由于某些原因,当我使用无法正常工作的 DataSource 属性时,这是我的代码(它只是我正在使用的一个虚拟列表,所以我可以看到我做错了什么)。

private void Form1_Load(object sender, EventArgs e)
{
    List<Client> list = new List<Client>();
    Client client1 = new Client(1, "joro", "2014-12-12", 5);
    Client client2 = new Client(2, "moro", "2015-1-12", 3);
    list.Add(client1);
    list.Add(client2);
    dataGridClients.DataSource = list;
}

和“客户端”类(它与我想要将信息放入网格的数据库中的表相同)

public class Client
{
    private int clientId;
    private string clientName;
    private string dateStarted;
    private int cycleLength;

    public Client(int id, string name, string date, int length)
    {
        clientId = id;
        clientName = name;
        dateStarted = date;
        cycleLength = length;
    }
}

因此当表单加载时,数据网格中没有任何内容。我是这方面的新手,我以前从未使用过数据网格,所以我做错了什么?

最佳答案

当您设置 DataGridView.DataSource 值时,网格应该为列表中对象的 public properties 创建列

Client 类中只有private variables。创建相应的属性

public class Client
{
   private int clientId;
   // editable property => editable column
   public int ClientId { get { return clientId; } set {clientId = value;} }

   private string clientName;
   // readonly property => readonly column
   public string ClientName { get { return clientName; } }

   // ... same for the rest variables
}

关于c# - 无法从列表中的 DataGridView 中加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33362702/

相关文章:

c# - 使用 CheckedListBox 设置 DataGridView 列的可见性

c# - 为什么在 Select 之前运行 LINQ OrderBy 会花费更多时间?

c# - 反射扩展法

c# - 如何控制多个线程对对象集合的访问?

c# - WinForms 中的图标

c# - 将 ü 转换为 ü

c# - 为什么 lock(this) {...} 不好?

c# - 在 Azure 中发布时 Web 应用程序行为不同

c# - 将光标保持在数据 GridView 的特定列内

silverlight - 您可以在 Silverlight DataGrid 中将 ScrollIntoView() 与 PagedCollectionView 一起使用吗?