简体   繁体   中英

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.

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.

My question is, how do I go about getting the details of each of the objects in the list to display in the 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 . 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 .

2) Data bind the DGV. There's many articles about databinding to a 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 . 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.

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

use as 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; 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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