.net - DataGridView 的 BindingList<T> 数据源

标签 .net datagridview bindinglist

我有一个 BindingList,我想将其用于 DataGrid View 上的数据源。
我将 dataGridView1 和按钮 1 添加到表单中。 当我按下按钮时,dataGridView 上没有显示任何内容。如果我使用 DataTable 作为数据源,它工作正常。我一定错过了一些简单的东西。

public partial class Form1 : Form
{
    BindingList<ClassificationInfo> boundList;
    ClassificationInfo item;

    private void button1_Click(object sender, EventArgs e)
    {
        boundList = new BindingList<ClassificationInfo>();

        item = new ClassificationInfo();
        item.bExclude = 1;
        item.iColor = 123456;
        item.szDescription = "Test line 1";
        boundList.Add(item);    

        item = new ClassificationInfo();
        item.bExclude = 0;
        item.iColor = 7890123;
        item.szDescription = "Test line 2";
        item.iOrder = 2;
        boundList.Add(item);

        dataGridView1.DataSource = boundList;
    }    

    public class ClassificationInfo
    {
        public int iColor;
        public int iOrder;
        public string szDescription;
        public int bExclude;
    }
}

最佳答案

将 ClassificationInfo 上的公共(public)字段转换为属性。

public class ClassificationInfo 
{ 
    public int iColor { get; set; }
    public int iOrder { get; set; }
    public string szDescription { get; set; }
    public int bExclude { get; set; }
} 

几乎所有情况下的数据绑定(bind)都依赖 TypeDescriptor ,它使用 PropertyDescriptors 来发现属性。字段被忽略(因为它们应该如此 - 它们应该被封装),因此您的数据绑定(bind)不起作用。

关于.net - DataGridView 的 BindingList<T> 数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3787943/

相关文章:

c# - 删除列表中最后一项时数据绑定(bind)的 InvalidOperationException

c# - 使 SortableBindingList 使用稳定排序的最简单方法

c# - 我如何知道分配给线程的实际时间片?

.net - 适用于 .NET 的 Google API(第 2 版)是否可再发行?

c# - Datagridview 未在已打开的表单上更新

C# 只想在数据表中显示时间(不是日期)

c# - OLEDB,在没有前导撇号的情况下编写 Excel 单元格

.net - 使用 ADO.net(OLEDB) 导入 UTF-8 CSV 文件

MySQL 字符串未转换为 .NET 时间