2017-01-03 60 views
1

我一直在使用BindingLists来显示在我的应用程序中运行的线程的对象数据。 这一直很好。C#绑定列表<T>作为DataGrid的数据源

现在我想在DataGridView中显示我自己的对象的属性,空的BindingList的绑定成功没有麻烦。 但是将元素添加到列表时,我得到一个异常的DataGridView

其工作原理的代码说明必须有列:

BindingList<Thread> threads = new BindingList<Thread>(); 
dgThreadStates.DataSource = new BindingSource() { DataSource = threads }; //DataGridView 
Thread t = new Thread(new ParameterizedThreadStart(handler.handleEntries)); 
threads.Add(t); 

然而,这似乎并没有工作:

public class Customer 
{ 
    public System.Guid GUID; 

    public string FirstName; 
    public string MiddleName; 
    public string LastName; 

    public string Postcode; 
    public string HouseNo; 
    public string StreetName; 
    public string City; 
} 

的方法:

BindingList<Customer> savedCustomers = new BindingList<Customer>(); 
dgvCustomers.DataSource = new BindingSource() { DataSource = savedCustomers }; //DataGridView 
savedCustomers.Add(new Customer()); 

我会得到THI小号例外:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll. Additional Information: No row can be added to a DataGridView control that does not have columns. Columns must be added first. 
+2

您在您的客户类中使用字段,但绑定与属性不是字段一起使用。 – Ralf

+0

@Ralf你是对的!请张贴这个答案,以便我可以标记它。 –

回答

1

数据绑定的工作原理与性能并不领域。 DataGridView不会在您的类中找到用于生成列的属性(我假定您在网格中使用autocreatecolumns),并拒绝没有任何列的工作。

所以你需要用(atleast自动)属性替换你的字段。

public class Customer 
{ 
    public System.Guid GUID { get; set; } 
    // etc. 
} 
0

以下是可能的解决方案

var list = new List<users>() 
{ 
    new Person { Name = "Robin", }, 
    new Person { Name = "Cleef", }, 
}; 
var bindingList = new BindingList<users>(list); 
var source = new BindingSource(bindingList, null); 
grid.DataSource = source;