该代码假定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
的代码来构建数据集
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);
}
}
然后设置用于从列表框DataGridView中的数据源。
listBox1.SelectedIndexChanged += (s, e) =>
{
ushort yr = (ushort)listBox1.SelectedItem;
dataGridView1.DataSource = dataSet.Tables[yr.ToString()];
};
!!!重要!
由于您的DataGridView已经定义了数据绑定前12列,您需要设置DataGridView
相同的每一列的数据表的列名的DataPropertyName
property或绑定将添加新列。
很抱歉忘记提及AcceptableMonths是一个枚举。 我想我现在可以实现一个INotifyPropertyChanged,但这不会有问题。 尽管如此,一个非常好的解决方案。 :) 非常感谢。我花了很多年才弄明白这一点。 ;) – JumbleGee 2014-10-20 18:29:10
很高兴我能帮到你。然而,最难的部分是,如果你将'Month'列表直接绑定到'DataGridView',它们将被添加为12行,而不是列,所以首先你必须构建一个适合“回归”的'DataTable' “列和行定义...如果Month as Row和Category作为Column是可以接受的,你可以直接绑定到你的'Year'类(一个BindingList)。 – kennyzx 2014-10-21 01:33:36
是的,我已经尝试过它,它正在工作。必须做一些调整,但现在我有线索并知道从哪里开始。再次感谢 ;) – JumbleGee 2014-10-22 18:13:58