2014-10-18 95 views
0

我正在编写一个计算我的扩展的应用程序。我有一个固定的DatagridView有12列(1月 - 12月)和5行(分类)。 我的课表:固定DataGridView数据绑定

Month -> contains the value of all 5 categories 
Year -> SortedList<MonthSet.AcceptableMonths, Month> 
AnnualSpend -> SortedList<ushort, Year> 

在启动程序将分析在相关的类一个XML文件,并存储数据。 现在我有5个属性(每个类别1)的类“月”,并希望绑定一个特定的月份到相应的列。 我将能够通过每个单元格和插入值“手动”,但我不知道如果这是一个好方法。此外,我能够绑定我的所有年份,但我不知道如何绑定数据(当我从列表框中选择一年时)。我试图按照正常的方式去做,但是我会失去所有定义的行,并且会添加新的列。 我甚至不知道这是否像我想的那样工作。如果没有,那么我必须通过每个单元格。

我希望这是可以理解的,有人可以告诉我,如果这甚至会起作用。

感谢)

回答

0

该代码假定AcceptableMonths是定义如下,因此它可以从一个整数被铸造的Enum

enum AcceptableMonths 
{ 
    JAN, FEB, MAR, ARP, MAY, JUN, JLY, AUG, SEP, OCT, NOV, DEC 
} 

您可以构建从AnnualSpend一个DataSet,然后将其表格中的一个(一年的费用)为DataGridViewDataSource。从你的类到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或绑定将添加新列。

+0

很抱歉忘记提及AcceptableMonths是一个枚举。 我想我现在可以实现一个INotifyPropertyChanged,但这不会有问题。 尽管如此,一个非常好的解决方案。 :) 非常感谢。我花了很多年才弄明白这一点。 ;) – JumbleGee 2014-10-20 18:29:10

+0

很高兴我能帮到你。然而,最难的部分是,如果你将'Month'列表直接绑定到'DataGridView',它们将被添加为12行,而不是列,所以首先你必须构建一个适合“回归”的'DataTable' “列和行定义...如果Month as Row和Category作为Column是可以接受的,你可以直接绑定到你的'Year'类(一个BindingList)。 – kennyzx 2014-10-21 01:33:36

+0

是的,我已经尝试过它,它正在工作。必须做一些调整,但现在我有线索并知道从哪里开始。再次感谢 ;) – JumbleGee 2014-10-22 18:13:58