【问题标题】:DataSource doesn't show data when updatedDataSource 更新时不显示数据
【发布时间】:2015-10-15 20:02:11
【问题描述】:

我有一个 dataGridView,它应该使用一个列表作为数据源。运行应用程序时,它会显示带有列的网格(自动生成)。 当一个新的 Person 对象被创建并添加到名为 Persons 的列表中时,它只添加一个空行。在此之后添加新人员时,不会进行任何更改。

系统在 MainForm 中使用一个名为 Project 的属性,它存储用于网格的列表。

public partial class MainForm : Form
{
    public static DataProject Project { get; set; }

    public MainForm()
    {
        InitializeComponent();
        //show a dialog, creating the Project-object
        BindingSource bs = new BindingSource();
        bs.DataSource = Project.Persons;
        dataGridView1.DataSource = bs;
    }

    private void buttonAddPerson_Click(object sender, EventArgs e)
    {
        //show a dialog, creating a person and adding him to Project.Person (list).
        dataGridView1.Refresh();
        dataGridView1.Update();
    }
}

这是 DataProject 对象:

public class DataProject
{
    public string Name { get; set; }
    public List<Person> Persons { get; set; }

    public DataProject()
    {
        Persons = new List<Person>();
    }
}

【问题讨论】:

标签: c# datagridview datasource


【解决方案1】:

为 BindingSource 创建一个全局变量

BindingSource bs = new BindingSource();

在按钮上单击只需重置此绑定源

bs.ResetBindings(false);

【讨论】:

    【解决方案2】:

    dataGridView1.DataBind();在最后添加这个。我曾经遇到过同样的问题,它对我有用!

    public MainForm()
        {
            InitializeComponent();
            //show a dialog, creating the Project-object
            BindingSource bs = new BindingSource();
            bs.DataSource = Project.Persons;
            dataGridView1.DataSource = bs;
            dataGridView1.DataBind();  
        }
    

    【讨论】:

    • 实际上是BindingSource中的ResetBindings(),而不是DataGridView。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 2023-04-06
    相关资源
    最近更新 更多