C# 修复了DataGridView数据绑定
我正在写一个计算我的费用的应用程序。我有一个固定的DatagridView,有12列(一月到十二月)和5行(类别)。 我的班级:C# 修复了DataGridView数据绑定,c#,.net,datagridview,C#,.net,Datagridview,我正在写一个计算我的费用的应用程序。我有一个固定的DatagridView,有12列(一月到十二月)和5行(类别)。 我的班级: Month -> contains the value of all 5 categories Year -> SortedList<MonthSet.AcceptableMonths, Month> AnnualSpend -> SortedList<ushort, Year> Month->包含所有5个类别的值 年份->
Month -> contains the value of all 5 categories
Year -> SortedList<MonthSet.AcceptableMonths, Month>
AnnualSpend -> SortedList<ushort, Year>
Month->包含所有5个类别的值
年份->分类列表
年度支出->分类列表
在启动时,程序将解析XML文件并将数据存储在相关类中。
现在,我有了具有5个属性的类“Month”(每个类别一个),并希望将特定月份绑定到相应的列。
我可以遍历每个单元格并“手动”插入值,但我不知道这是否是一个好方法。我还可以在列表框中绑定所有年份,但我不知道如何绑定数据(当我从列表框中选择年份时)。我试着用正常的方法来做,但是我会丢失所有定义的行,并且会添加新的列。
我甚至不知道这是否像我想的那样起作用。如果不是的话,我很可能要通过每个细胞
我希望这是可以理解的,有人能告诉我这是否有效
谢谢;) 该代码假定
AcceptableMonths
是一个定义如下的Enum
,因此可以从整数强制转换
enum AcceptableMonths
{
JAN, FEB, MAR, ARP, MAY, JUN, JLY, AUG, SEP, OCT, NOV, DEC
}
您可以从年度支出
构建数据集
,然后将其中一个表(年度支出)设置为数据网格视图
的数据源
。从类到数据集的映射是
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在数据绑定之前已经定义了12列,因此需要将
DataGridView
中每列的名称设置为与DataTable的列名相同,否则绑定将添加新的列。很抱歉,忘了提及AcceptableMonths是一个枚举。我想我现在可以实现INotifyPropertyChanged,但这不会有问题。不过,这是一个非常好的解决方案。:)非常感谢你。我要花很长时间才能弄明白这一点很高兴我能帮忙。然而,困难的部分是,如果您将月份的列表直接绑定到DataGridView
,它们将被添加为12行,而不是列,因此首先您必须构建一个DataTable
,该表符合“还原”列和行定义……如果可以接受月份作为行和类别作为列,你可以直接绑定到你的Year
类(一个绑定列表)。是的,我已经尝试过了,它正在工作。我必须做一些调整,但现在我有了一个线索,知道从哪里开始。再次感谢;)
listBox1.SelectedIndexChanged += (s, e) =>
{
ushort yr = (ushort)listBox1.SelectedItem;
dataGridView1.DataSource = dataSet.Tables[yr.ToString()];
};