如何从一个数据网格视图计算总价格并对其进行更新,然后在另一个数据网格视图中显示它GridViwe C#



我做的是一个披萨菜单,我有 3 个 dataGridView,第一个显示菜单,第二个显示所选披萨的成分,第三个显示成分列表(用户可以添加去除成分(。问题是我需要通过自动更新来计算第二个 DGV 的成分价格,然后在第一个 DGV 中显示最终价格

pizzaGrid.DataSource = SelectedList;
DataGridViewCell pizzacell = MenuGrid.CurrentCell;
DataGridViewCell ingrecell = IngredientCell.Currentcell;
int total = 0;
for(int i = 0; i < ingredientList.Count; i++)
{
    Ingredient ingre = ingredientList[i];
    if(ingredientList.Contain(i))
    {
        total++;
        SelectedList.Add(i);
    }
}
如果我

理解你的问题是正确的,你想从数据网格中计算列中所有值的总价格,你可以尝试这样的事情

int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
}
label1.text = sum.ToString();

你应该构建一个看起来像这样的方法:

private double calculatePrice()
{
    double sum = 0; //Double, because we are dealing with money, which is a decimal
    for(int i = 0; i < IngredientGrid.Rows.Count; i++)
    {
        sum += Convert.ToDouble(IngredientGrid.Rows[i].Cells[1].Value); //This takes the value of your selected cell within your ingredients datagrid (they need to be only numbers, no letters since we're converting to a double)
    }
    return sum;
}

然后调用此方法,例如更改索引或像这样:

label1.Text = calculatePrice().ToString();

最新更新