【问题标题】:How to calculate the total price from one data grid view and update it then show it in another dataGridViwe C#如何从一个 datagridview 计算总价并更新它然后在另一个 dataGridView C# 中显示
【发布时间】:2018-01-19 08:47:10
【问题描述】:

正在做的是一个披萨菜单,我有 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);
    }
}

【问题讨论】:

  • 到目前为止你写过代码吗?如果是这样,请将其添加到您的问题中,如果不是:StackOverflow 是针对特定实现问题的,而不是让我们为您编写代码。参考:stackoverflow.com/help/how-to-ask
  • @FreekW,我试过 for 循环,但没用
  • 然后添加那个代码,也添加添加项目的代码(这里是披萨和配料),因为你的描述比较模糊。
  • 我附上了我试过@FreekW的代码截图

标签: c# datagridview window


【解决方案1】:

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

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();

【讨论】:

    【解决方案2】:

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

    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();
    

    【讨论】:

    • 我做过类似的事情,但是我没有使用转换,因为我在方法中键入了类中的代码并且它可以工作。但问题是它不会自动更新,我需要点击计算价格的单元格然后它会更新
    • 如果你想update 一些东西,你会想要更新是在你做了一些值得更新的事情之后,对吧?每当您执行此操作时,都会调用此方法。 (您可以更新FormLoad 或与该表格进行的任何互动)。如果您希望每年更新,请创建Timer。将interval 设置为所需的数量,您就完成了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多