1

这可能看起来很简单,但我不知道该怎么做。我不是 C# 数据绑定方面的专家。

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

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作为DatagridViewUserData 列表成员的控件的数据源。

谢谢

4

2 回答 2

5

首先,您必须以某种方式公开您的 customerinfo 列表(它现在是私有的,因此您无法从 IntVector 类之外获取它)。

如果是公开的:

BindingSource bs = new BindingSource(); 

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

datagridview.DataSource = bs;

此外,如果您想以编程方式修改列表并希望将这些更改传播到控件,您可能需要考虑使用 BindingList 而不是 List (这里解释了List<T> 与 BindingList<T >

您的 CustomerInfo 类是什么样的?我假设您想将 DataGridView 的列绑定到 CustomerInfo 类的公共属性,例如:

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

   private string somePrivateData;
}

现在,如果您的 DataGridView 中的 AutoGenerateColumns 设置为 true,那么将在您的 DataGridView 中自动创建 3 列“Id”、“Name”和“Address”。“somePrivateData”将被忽略。

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

// 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_Name";
datagridview.Columns.Add(col1);

DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
col2.DataPropertyName = "Address";
col2.HeaderText = "Address";
col2.Name = "column_Address";
datagridview.Columns.Add(col2);
于 2013-04-04T12:58:07.373 回答
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;

我希望这会有所帮助...

于 2013-04-04T13:03:11.427 回答