简体   繁体   English

用对象列表填充 datagridview

[英]populating datagridview with list of objects

I have a List that contains a series of transaction objects.我有一个包含一系列交易对象的列表。 What I'm trying to do is to display these transaction objects in a Datagridview control on loading a form, basically the Datagridview should represent something of a transaction register to display the data for each of the transaction objects in the list.我想要做的是在加载表单时在 Datagridview 控件中显示这些事务对象,基本上 Datagridview 应该代表事务寄存器的某些内容,以显示列表中每个事务对象的数据。

I must admit to a lack of experience when it comes to using Datagridviews and I'm having some difficulty with understanding what I need to do here.我必须承认在使用 Datagridviews 时缺乏经验,而且我在理解我需要在这里做什么时遇到了一些困难。

My question is, how do I go about getting the details of each of the objects in the list to display in the Datagridview?我的问题是,如何获取列表中每个对象的详细信息以显示在 Datagridview 中?

Here is my code.这是我的代码。

First the transaction class:首先是事务类:

public class Transaction
{
    // Class properties
    private decimal amount;
    private string type;
    private decimal balance;
    private string date;
    private string transNum;
    private string description;

    // Constructor to create transaction object with values set.
    public Transaction(decimal amount, string type, decimal currBal, string date, string num, string descrip)
    {
        this.amount = amount;
        this.type = type;
        this.balance = currBal;
        this.date = date;
        this.transNum = num;
        this.description = descrip;
    }

    // Get and Set accessors to allow manipulation of values.
    public decimal Amount
    {
        get
        {
            return amount;
        }
        set
        {
            amount = value;
        }
    }
    public string Type
    {
        get
        {
            return type;
        }
        set
        {
            type = value;
        }
    }
    public decimal Balance
    {
        get
        {
            return balance;
        }
        set
        {
            balance = value;
        }
    }
    public string Date
    {
        get
        {
            return date;
        }
        set
        {
            date = value;
        }
    }
    public string TransNum
    {
        get
        {
            return transNum;
        }
        set
        {
            transNum = value;
        }
    }
    public string Description
    {
        get
        {
            return description;
        }
        set
        {
            description = value;
        }
    }

    public decimal addCredit(decimal balance, decimal credit)
    {
        decimal newBalance;
        newBalance = balance + credit;
        return newBalance;
    }

    public decimal subtractDebit(decimal balance, decimal debit)
    {
        decimal newBalance;
        newBalance = balance - debit;
        return newBalance;
    }
    }
}

Now the code for the "Register" form:现在“注册”表单的代码:

    public partial class Register : Form
{
    List<Transaction> tranList = new List<Transaction>();

    public Register(List<Transaction> List)
    {
        InitializeComponent();
        this.tranList = List;
    }

    private void Register_Load(object sender, System.EventArgs e)
    {
        //regView represents the Datagridview that I'm trying to work with
        regView.AutoSize = true;
        regView.DataSource = tranList;
        regView.Rows.Add(tranList[0]);
    }
}

And here's the output I get.这是我得到的输出。寄存器输出

There's really two high level approaches to this.对此,确实有两种高级方法。

1) Add the manually created rows directly to the DataGridView . 1) 将手动创建的行直接添加到DataGridView In this case, you have to manually update/remove them as things change.在这种情况下,您必须在情况发生变化时手动更新/删除它们。 This approach is "ok" if you don't intend to alter/change the content of the display after you initialize it.如果您在初始化后不打算更改/更改显示内容,则此方法“可以”。 It becomes untenable if you do.如果你这样做,它就会变得站不住脚。

To add it directly, you need to create a DataGridViewRow , and populate it with the individual values, and then add the DataGridViewRow to the DataGridView.Rows .要直接添加它,您需要创建一个DataGridViewRow ,并用各个值填充它,然后将DataGridViewRow添加到DataGridView.Rows

2) Data bind the DGV. 2) 数据绑定DGV。 There's many articles about databinding to a DataGridView .有很多关于数据绑定到DataGridView文章。 In some cases, it's easier to just add your data to a DataTable , and then extract a DataView from that, and bind the DataGridView to the DataView .在某些情况下,将数据添加到DataTable ,然后从中提取DataView ,并将DataGridView绑定到DataView更容易。 Other people find it easier to directly bind to a collection.其他人发现直接绑定到集合更容易。

CodeProject has a decent article to get you started down that path, but a quick Google search will yield many other articles. CodeProject 有一篇不错的文章可以帮助您走上这条道路,但在 Google 上快速搜索会产生许多其他文章。

http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorial http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorial

use as DGV:用作 DGV:

DataGridView groupListDataGridView;

column:柱子:

DataGridViewTextBoxColumn groupListNameColumn;

column setup should be like this:列设置应如下所示:

groupListNameColumn.DataPropertyName = "name";

use this property, else all columns will be added.使用此属性,否则将添加所有列。

groupListDataGridView.AutoGenerateColumns = false;

populate like this:像这样填充:

private void populateGroupList() {
    groupListDataGridView.DataSource = null;
    formattedGroupList = new SortableBindingList<DataGridGroupObject>();
    foreach (GroupObject go in StartUp.GroupList) {
        DataGridGroupObject dggo = new DataGridGroupObject();
        dggo.id = go.Id;
        dggo.name = go.Name;
        formattedGroupList.Add(dggo);
    }
    groupListDataGridView.DataSource = formattedGroupList;
    groupListDataGridView.Invalidate();
}

and model:和型号:

public class DataGridGroupObject
{
    public int id { get; set; }      //this will be match id column
    public string name { get; set; } // this will be match name column
}

Simply add using System.Linq;只需using System.Linq;添加using System.Linq; at the top.在顶部。 Then you can do this:然后你可以这样做:

//This will create a custom datasource for the DataGridView.
var transactionsDataSource = tranList.Select(x => new
{
        Amount = x.amount,
        Type = x.type,
        Balance = x.balance,
        Date = x.date,
        TransNum = x.transNum
        Description = x.description
}).ToList();

//This will assign the datasource. All the columns you listed will show up, and every row
//of data in the list will populate into the DataGridView.
regView.DataSource = transactionsDataSource;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM