代码假定AcceptableMonths 是一个Enum,定义如下,因此可以从整数转换。
enum AcceptableMonths
{
JAN, FEB, MAR, ARP, MAY, JUN, JLY, AUG, SEP, OCT, NOV, DEC
}
您可以从AnnualSpend 构造一个DataSet,然后将其中一个表(年度费用)设置为DataGridView 的DataSource。从您的类到 DataSet 的映射是。
Month->A Column, Year->A DataTable, AnnualSpend->The entire DataSet
构造DataSet的代码
AnnualSpend annualSpend; //already populated
DataSet dataSet;
private void PopulateDataSet()
{
dataSet = new DataSet();
foreach (ushort yr in annualSpend.Keys)
{
Year year = annualSpend[yr];
DataTable tableOfYear = new DataTable(yr.ToString()); //as key to access the Table
//Adding columns
List<string> columnNames = new List<string>();
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
columnNames.Add(column.Name);
column.DataPropertyName = column.Name; //!!!Important!!!
tableOfYear.Columns.Add(new DataColumn(column.Name));
}
//Adding rows
DataRow newRowForFoodExpense = tableOfYear.NewRow();
//then 4 data rows for other expense categories...
//DataRow newRowForHouseRent = tableOfYear.NewRow();
for (int m = 0; m < columnNames.Count; m++)
{
newRowForFoodExpense[columnNames[m]] = year[(AcceptableMonths)m].Food;
//then 4 data rows for other expense categories...
}
tableOfYear.Rows.Add(newRowForFoodExpense);
//then 4 data rows for other expense categories...
dataSet.Tables.Add(tableOfYear);
}
}
然后从 ListBox 中为 DataGridView 设置 DataSource。
listBox1.SelectedIndexChanged += (s, e) =>
{
ushort yr = (ushort)listBox1.SelectedItem;
dataGridView1.DataSource = dataSet.Tables[yr.ToString()];
};
!!!重要!!!
由于您的DataGridView在DataBinding之前已经定义了12列,所以您需要将DataGridView的每一列的DataPropertyName property设置为与DataTable的列名相同,否则绑定会添加新列。