如何在C#中的2个datagridview之间制作公式

我需要一个让我控制2个datagridview之间的公式的类或者其他方式请给我一个链接以了解更多因为我不知道我正在寻找的操作的确切名称..如果你能做到我请求讨论和解释一个代码作为茶她她需要知识而不是做这个应用程序,我15岁,学校即将开始,所以我需要一个像我的英雄“卡普尔”的现场和互动帮助我的观点很难,我没有在网上找到任何答案,顺便说一句,我可以做一个计算列,但是在同一个表中,但是如果这个值在其他表格中,则无法计算列,我希望这次我发送我的信息正确! 😉

分享我的想法以实现一个解决方案,其中更改单元格中的值会更新另一个值

首先,创建一个类似CellRelation的类 – 其目的是建立2个网格单元之间的关系。

class CellRelation { DataGridCell SourceCell; DataGridCell DestinationCell; Func Formula; } 

其次,初始化

  1. 像你现在一样填充你的网格

  2. 对于您希望拥有公式的所有网格单元格,创建一个CellRelation实例并添加它做一个集合 – CellRelations

  3. 当您创建CellRelation的实例时 – >为其提供源单元格,目标单元格和委托。

例如,在您的情况下,如果您想计算剩余库存 –

Source Cell将被出售Inventry,目标单元格将被保留库存单元格。

公式(委托):我已经想到这个委托期望2个网格单元作为输入,并将结果作为十进制。

输入网格单元格将是“TotalInventoryCell”和“SoldInvenoryCell”,这个委托将是一个减去给定单元格值的函数。 委托的返回将是一个十进制值,您可以使用它来更新remainingig库存单元格

第三,更新网格1中的单元格的事件。

  1. 当单元格的值在网格中更改时,处理相应的事件。 在此事件处理程序上,遍历集合 – CellRelations,以查找是否存在需要根据输入的公式更新其值的依赖单元格。

  2. 如果找到更新单元格的条目,请执行委托(公式)并使用委托(公式)返回的小数值来更新目标单元格的值

如果您认为某些部分不清楚请告诉我,我会尝试提供样品


工作样本

我做了一个简短的工作样本(没有数据集)来演示我的方法。 我创建了一个包含一行和三列的datagridview – Total,Sold和Remaining

因此,每次对“已售出”单元格进行更改时,其余项目都会更新。

我使用单格制作,但同样可以扩展2格。 它有很大的改进空间,尤其是表达式部分,理想情况下它应该能够评估表达式树。

 class CellRelation { public DataGridViewCell SourceCell; public DataGridViewCell DestinationCell; public CellFormula Formula; } class CellFormula { public Func Operator; public DataGridViewCell Operand1; public DataGridViewCell Operand2; public decimal Evaluate() { return Operator(Operand1, Operand2); } } public partial class Form1 : Form { public Form1() { InitializeComponent(); } List cellRelations = new List(); private void Initialise_Click(object sender, EventArgs e) { var soldCell = this.dataGridView1[1, 0]; var remainingCell = this.dataGridView1[2, 0]; var totalCell = this.dataGridView1[0, 0]; // datagid values --- In your case this is from a dataset totalCell.Value = 10; soldCell.Value = 0; remainingCell.Value = 10; // initialise the relation / formula CellRelation relation = new CellRelation(); relation.SourceCell = soldCell; relation.DestinationCell = remainingCell; // thats the dependent cell relation.Formula = new CellFormula(); // here is a sample of subtraction formula : Subtracting Sold items for total items relation.Formula.Operator = new Func((p, v) => { return ((decimal.Parse(p.Value.ToString()))) - ((decimal.Parse(v.Value.ToString()))); }); relation.Formula.Operand1 = totalCell; relation.Formula.Operand2 = soldCell; cellRelations.Add(relation); } private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { //look up if there is an destination cell for the cell being updated var cellReln = cellRelations.FirstOrDefault(item => item.SourceCell.RowIndex == e.RowIndex && item.SourceCell.ColumnIndex == e.ColumnIndex); if (cellReln != null) { cellReln.DestinationCell.Value = cellReln.Formula.Evaluate(); } } 

}

编辑:请注意 – 我建议的方法是使用CellRelation和CellFormula具有类型为DataGridViewCell的属性。 因此它与UI技术紧密结合(在这种情况下为winform)。 理想情况下,此类解决方案应独立于UI技术。 如果你需要一个样本,它位于一个单独的业务层,请给我写评论。