C#计算DataGridView&中的Price and Quantity列显示总列数

时间:2015-03-23 02:52:25

标签: c#

大家好我想在DataGridView中计算以下内容如果按下“计算”按钮,价格列和数量列将相乘,它将显示在总列中。以下是添加项目名称,价格和数量的代码。任何帮助将不胜感激谢谢!

    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;


    }

1 个答案:

答案 0 :(得分:1)

您需要首先将dataGridView单元格值转换为十进制或双数据类型,然后将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);
}