简体   繁体   English

C#计算DataGridView中的“价格和数量”列并显示为“总计”列

[英]C# Calculate Price and Quantity column in DataGridView & Display to Total Column

Hi everyone I wanted to calculate the following in DataGridView If button " Calculate" is pressed Price column and Quantity column will multiply and it will be displayed in Total Column. 大家好,我想在DataGridView中计算以下内容:如果按下按钮“计算”,则价格列和数量列将相乘,并将显示在总计列中。 Below is the code for adding Item name,Price and Quantity. 下面是添加商品名称,价格和数量的代码。 Any help would be appreciated Thank you! 任何帮助,将不胜感激,谢谢!

    private void button1_Click(object sender, EventArgs e)
    {
        dataGridView1.Rows.Add();
        dataGridView1.Rows[0].Cells[0].Value = textBox1.Text;
        dataGridView1.Rows[0].Cells[1].Value = textBox2.Text;
        dataGridView1.Rows[0].Cells[2].Value = textBox3.Text;


    }

You need to cast the dataGridView cell value into decimal or double data type first then round up with Math.Round function into 2 or 3 decimal point whatever you need. 您需要先将dataGridView单元格值转换为十进制或双Math.Round数据类型,然后根据需要将Math.Round函数Math.Round入为2或3个小数点。

private void button1_Click(object sender, EventArgs e)
{
    int iNewRowIndex = dataGridView1.Rows.Add();
    dataGridView1.Rows[iNewRowIndex].Cells["Name"].Value = textBox1.Text;
    dataGridView1.Rows[iNewRowIndex].Cells["price"].Value = textBox2.Text;
    dataGridView1.Rows[iNewRowIndex].Cells["qty"].Value = textBox3.Text;

    dataGridView1.Rows[iNewRowIndex].Cells["Total"].Value = Math.Round(Convert.ToDecimal(dataGridView1.Rows[iNewRowIndex].Cells["price"].Value) * Convert.ToDecimal(dataGridView1.Rows[iNewRowIndex].Cells["qty"].Value), 2);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM