【问题标题】:BindingList<T> datasource for DataGridViewDataGridView 的 BindingList<T> 数据源
【发布时间】:2011-04-16 19:41:57
【问题描述】:

我有一个 BindingList,我想将它用于 DataGrid 视图上的数据源。
我将 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;
    }
}

【问题讨论】:

    标签: .net datagridview bindinglist


    【解决方案1】:

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

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

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

    【讨论】:

    • 这行得通。谢谢。你是如何正确格式化我的帖子的?我以为我在代码标签之间发布了它,但是发布时整个代码块没有突出显示。
    • 这个网站不使用代码标签,不知道你从哪里得到的。在编辑帖子时,您可以在右侧有一个摘要,或者您只需单击编辑器中的代码按钮(1 和 0)并选择代码(代码格式为开头的 4 个空格)行)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2011-07-17
    • 2021-09-15
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多