2013-04-04 103 views
0

这看起来很简单,但我无法弄清楚如何实现它。我不是C#中Databinding的专家。如何将数据源设置为C#中的Datagridview控件#

我有类对象(这是一个嵌套类),它看起来像这样的列表:

public class IntVector 
{ 
    private string customerid; 
    private string hash_id; 
    private string client_name; 
    private string mobile_no; 
    private string address; 

    //Table 

    private List<CustomerInfo> customerinfo; 
} 

我有IntVector

private List<IntVector> UserData; 

现在列表如何设置CustomerInfo为作为列表UserData成员的DatagridView控件的数据源。

感谢

+2

http://stackoverflow.com/questions/1228539/how-to-bind-list-to-datagridview – phadaphunk 2013-04-04 12:35:37

+0

我很抱歉,我不明白的帖子和解决方案。你能否详细说明一下?谢谢 – Kiran 2013-04-04 12:48:51

回答

3

首先,你必须以某种方式暴露你的customerinfo列表(现在是私人的,所以你不能从你的intVector的类的外部得到它)。

如果它是市民:

BindingSource bs = new BindingSource(); 

int indexInUserDataList = 0; 
bs.DataSource = UserData[indexInUserDataList].customerinfo; 

datagridview.DataSource = bs; 

此外,你可能想,如果你想通过程序修改列表,并希望这些更改传播到控制(这里的差异考虑使用,而不是名单的BindingList解释为List<T> vs BindingList<T> Advantages/DisAdvantages

你的CustomerInfo类是什么样的?我想你想的DataGridView的列绑定到CustomerInfo类的公共属性,exsample:

class CustomerInfo 
{ 
    public int Id {get;set;} 
    public string Name {get;set;} 
    public string Address {get;set;} 

    private string somePrivateData; 
} 

现在,如果你的DataGridView的AutoGenerateColumns设置为true,那么3列“ID”,“名称”和“地址“将自动在你的DataGridView中创建。 “somePrivateData”将被忽略。

如果你想自己定义collumns,你可以做这样的:

// make sure to do it before binding DataGridView control 
datagridview.AutoGenerateColumns = false; 

DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn(); 
col1.DataPropertyName = "Name"; 
col1.HeaderText = "Customer name"; 
col1.Name = "column_Address"; 
datagridview.Columns.Add(col1); 

DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn(); 
col2.DataPropertyName = "Address"; 
col2.HeaderText = "Address"; 
col2.Name = "column_Name"; 
datagridview.Columns.Add(col2); 
+0

太棒了。非常感谢您的时间。我将尝试实施这些更改。谢谢 – Kiran 2013-04-04 13:19:36

0

您需要设置客户的私人列表为市民:

public class IntVector 
{ 
    private string customerid; 
    private string hash_id; 
    private string client_name; 
    private string mobile_no; 
    private string address; 

    //Table 

    public List<CustomerInfo> customerinfo; 

}

private List<IntVector> UserData; 

//Populate the UserData list here 

然后,您可以将数据源设置为DataGridView,例如:

DataGridView.DataSource = UserData[0].customerinfo; 

我希望帮助...

相关问题