6

我不明白为什么我的 DataGridView 一直为空(没有行,没有自动生成的列):

BindingList<MyObject> bList = new BindingList<MyObject>();
 fileStream.Position = 0;
 MyObject.Deserialize(fileStream).ForEach(
     j => bList.Add(j));

 this.bindingSource1.SuspendBinding();

 this.dataGridView1.Columns.Clear();
 this.dataGridView1.AutoGenerateColumns = true;
 this.dataGridView1.Enabled = false;
 this.dataGridView1.Invalidate();
 this.bindingSource1.DataSource = bList;
 this.dataGridView1.DataSource = bindingSource1;
 this.bindingSource1.ResumeBinding();
 this.dataGridView1.Enabled = true;
 this.dataGridView1.Refresh();

其中 MyObject 定义为

public class MyObject
{
    public DateTime CreationDate;
    public string CreationId;

    public static List<MyObject> Deserialize(Stream s)
    {
        XDocument xml = XDocument.Load(s);

        var ps = from p in xml
                      .Descendants("p")
                      .Descendants("object")
                  select
                      new MyObject
                      {
                          CreationId = p.Attribute("creationid").Value
                      };

        return ps.ToList();
    }

}

此外,如果我如下明确设置列,则会将行添加到网格中,但它们都是空的

DataGridViewTextBoxColumn dc = new DataGridViewTextBoxColumn();
            dc.DataPropertyName = "CreationDate";
            dc.HeaderText = "CreationDate";
            dc.Name = "CreationDate";
            dc.Visible = true;
            dc.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            this.dataGridView1.Columns.Add(dc);

            dc = new DataGridViewTextBoxColumn();
            dc.DataPropertyName = "CreationId";
            dc.HeaderText = "CreationId";
            dc.Name = "CreationId";
            dc.Visible = true;
            dc.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            this.dataGridView1.Columns.Add(dc);
4

1 回答 1

6

在 Winforms 项目中,尝试此代码(您已发布的模拟器的类型 & it works !)然后映射/调试到您现有的代码以缩小问题范围:-

    DataGridView dgv = new DataGridView();
    //Note: AutogenerateColumns is true by default
    BindingSource bs = new BindingSource();
    BindingList<Customer> bList = new BindingList<Customer>();

    // Fill bList with Customers
    bList.Add(new Customer(){Name="John"});

    bs.DataSource = bList;
    dgv.DataSource = bs;

    this.Controls.Add(dgv);

MyObject等价物:-

public class Customer
    {
        public string Name { get; set; }
    }

因此,to Debug your code 通过映射到上述一个,您可以删除这些位 -

 this.bindingSource1.SuspendBinding();
 this.dataGridView1.Columns.Clear();
 this.dataGridView1.AutoGenerateColumns = true;
 this.dataGridView1.Enabled = false;
 this.dataGridView1.Invalidate();
 this.bindingSource1.ResumeBinding();
 this.dataGridView1.Enabled = true;
 this.dataGridView1.Refresh();

just have this在第一次审判中 -

 this.bindingSource1.DataSource = bList;
 this.dataGridView1.DataSource = bindingSource1;
于 2012-06-18T09:30:04.687 回答