将通用数据绑定到DataGridView

我正在尝试创建一个通用的DataGridView,它可以基于任何数据类型的列表生成。 为此,我创建了一个具有通用类型T的用户控件,并将其实例添加到另一种形式时,使用希望填充DataGridView的类对其进行了初始化。 我还创建了一种方法,该方法根据提供的数据列表来设置通用表绑定。

public partial class UCTabelaDinamica<T> : UserControl
{
    private BindingSource TableSource { get; set; }
    private BindingList<T> TableList { get; set; }

    public UCTabelaDinamica()
    {
        InitializeComponent();
    }

    public void SetTableBindings(IList<T> tableData)
    {
        TableList = new BindingList<T>(tableData);
        TableSource = new BindingSource(TableList,null);

        dtTabela.AutoGenerateColumns = true;
        dtTabela.DataSource = TableSource;
    }
}

现在,要以这种形式使用此用户控件,我将其实例化如下:

private void InitializeComponent()
    {
        this.ucTabelaDinamica1 = new DataGridViewBuilderImproved.UCTabelaDinamica<Person>();
        this.SuspendLayout();
        // 
        // ucTabelaDinamica1
        // 
        this.ucTabelaDinamica1.Location = new System.Drawing.Point(12,12);
        this.ucTabelaDinamica1.Name = "ucTabelaDinamica1";
        this.ucTabelaDinamica1.Size = new System.Drawing.Size(475,337);
        this.ucTabelaDinamica1.TabIndex = 0;
        // 
        // Form1
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F,13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(499,361);
        this.Controls.Add(this.ucTabelaDinamica1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.ResumeLayout(false);

    }

    #endregion

    private UCTabelaDinamica<Person> ucTabelaDinamica1;

然后,我填充表格:

private void Form_Load(object sender,EventArgs e)
    {
        List<Person> people = new List<Person>
        {
            new Person
            {
                name = "Joao",age = 18
            },new Person
            {
                name = "Pedro",age = 21
            }
        };

        ucTabelaDinamica1.SetTableBindings(people);
    }

问题是表格以表格形式显示,但没有数据显示或创建了列,我不明白为什么。我搜索并看到了与此相关的不同主题,说先使用BindingList,然后再使用BindingSource,但似乎没有任何效果。帮不上忙吗?

更新:

正如@Jimi所建议的,我将通用T类型移至SetTableBindings函数,但该表仍未向我显示任何数据

public partial class UCTabelaDinamica : UserControl
{
    private BindingSource TableSource { get; set; }

    public UCTabelaDinamica()
    {
        InitializeComponent();
    }

    public void SetTableBindings<T>(IList<T> tableData)
    {
        TableSource = new BindingSource(new BindingList<T>(tableData),null);

        dtTabela.AutoGenerateColumns = true;
        dtTabela.DataSource = TableSource;
    }
}
wannabe321 回答:将通用数据绑定到DataGridView

我只是想知道发生了什么事。

我的Person类具有以下内容:

partitionBy

我将其更改为:

 public class Person
{
    public string name;
    public int age;
}

现在它可以完全正常工作了。

本文链接:https://www.f2er.com/3095631.html

大家都在问