简体   繁体   English

无法从 List<> 获取数据以填充数据网格视图

[英]can't get data from List<> to populate data grid view

From examples, this seems like it should be very straightforward, but for some reason I can't get data from a List<> to populate a data grid view.从示例来看,这看起来应该非常简单,但由于某种原因,我无法从 List<> 获取数据来填充数据网格视图。 I have created a class with 3 fields, created a list of the class and assigned the list to the DataSource property of a DGV.我创建了一个包含 3 个字段的类,创建了一个类列表并将该列表分配给 DGV 的 DataSource 属性。

The list is correctly populated with information, the DGV displays the proper number of rows, but all the textboxes are blank.该列表正确填充了信息,DGV 显示了正确的行数,但所有文本框都是空白的。 Can someone please show me what is wrong?有人可以告诉我有什么问题吗?

List<clsCHPChassis> myList = new List<clsCHPChassis>();

clsCHPChassis chassis1 = new clsCHPChassis("Rear Port", "Management", "192.168.1.1");
clsCHPChassis chassis2 = new clsCHPChassis("Front USB", "Local", "10.10.10.1");

myList.Add(chassis1);
myList.Add(chassis2);

dgv.DataSource = myList;

clsCHPChassis definition: clsCHPChassis定义:

public class clsCHPChassis 
{
    public string Site = string.Empty;
    public string ChassisName = string.Empty;
    public string IP = string.Empty;

    public clsCHPChassis(string newSite, string newChassisName, string newIP)
    {
        Site = newSite;
        ChassisName = newChassisName;
        IP = newIP;
    }
}

List itself is not enough to set as datasource. List 本身不足以设置为数据源。 you have to use BindingList<T> and BindingSourse along with it你必须同时使用BindingList<T>BindingSourse

Another and simple solution is use DataTable as DataSourse另一个简单的解决方案是使用 DataTable 作为 DataSourse

 DataTable table = new DataTable("Table");
 table.Columns.Add("Site", typeof(string));
 table.Columns.Add("ChassisName", typeof(string));
 table.Columns.Add("IP", typeof(string)); 

 table.Rows.Add("Rear Port", "Management", "192.168.1.1");
 table.Rows.Add("Front USB", "Local", "10.10.10.1");

 dgv.DataSource = table;

Only public properties are databound:只有公共属性是数据绑定的:

public class clsCHPChassis {
    public string Site { get; set; }
    public string ChassisName { get; set; }
    public string IP { get; set; }
}

Slai was able to solve the problem. Slai 能够解决这个问题。 His answer that only properties of the class are databound was the solution.他的答案是,只有类的属性是数据绑定的,这就是解决方案。 Changing the 3 fields to properties in the class definition to properties fixed it!将类定义中的 3 个字段更改为属性修复了它!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM