我有一个包含一系列事务对象的列表。我想要做的是在加载表单时在Datagridview控件中显示这些事务对象,基本上Datagridview应该代表一个事务注册表来显示列表中每个事务对象的数据。使用对象列表填充datagridview
当谈到使用Datagridviews时,我必须承认缺乏经验,并且在理解我需要在这里做什么时遇到一些困难。
我的问题是,如何获取列表中每个对象的详细信息以显示在Datagridview中?
这是我的代码。
首先是交易类:
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;
}
}
}
现在的 “注册” 形式的代码:
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]);
}
}
而这里的输出我得到。
我曾考虑过数据绑定,因为它似乎是最缺憾解决方案,因为它占的任何更改数据资源。 编辑:我打得太快。我试图说我没有完全确定数据绑定,因为我以前没有真正做过。我会看看你提供的链接,谢谢。 – morris295 2013-04-28 01:30:10
当你不熟悉它时,起初有点复杂,但随着时间和练习变得更容易(尽管它仍然可以为你提供许多令人沮丧的时刻)。上面的情况似乎应该是一个简单的例子,所以祝你好运。如果遇到他们,请随时回复更具体的问题。 – Gjeltema 2013-04-28 02:23:12
我结束了使用数据绑定,谢谢你的指导,这是相当有益的。你为此救了我一大堆的悲伤。 – morris295 2013-04-28 02:24:35