【问题标题】:How to multiply data of two columns for third column in datagridview如何将datagridview中第三列的两列数据相乘
【发布时间】:2013-09-10 03:29:33
【问题描述】:

我想将两列的数据相乘,显示在第三列。

例如:

1st Column: Quantity
2nd Column: Rate
3rd Column: Price

当用户在价格列中自动输入Quantity=2rate=50等数量和费率数据时,我想乘以我希望出现100

同时,当用户在数量列中自动输入Price=100rate=50等数量和费率数据时,我想进行除法,我希望出现2

并且 当用户在速率列中自动输入Price=100Quantity=2等数量和速率数据时,我希望出现50

这三个将发生在同一个datagridview中。用户只输入这三个中的任意两个字段,第三个会自动出现。

使用 C#、VS2008、SQL 2008

private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    int quantity,rate; 
    for (int i = 0; i < dataGridView2.Rows.Count; i++) 
    { 
        if(int.TryParse(dataGridView2.Rows[i].Cells[1].Value.ToString(), out quantity) && int.TryParse(dataGridView2.Rows[i].Cells[2].Value.ToString(), out rate)) 
        { 
             int price = quantity * rate; dataGridView2.Rows[i].Cells[3].Value = price.ToString(); 
        } 
    } 
}

我写了这段代码。那里显示一个错误。对象引用未设置为

上的对象实例
if(int.TryParse(dataGridView2.Rows[i].Cells[1].Value.ToString(), out quantity) && int.TryParse(dataGridView2.Rows[i].Cells[2].Value.ToString(), out rate)) 

这一行。


我想这样做。用户可以填写这 3 个字段中的任意 2 个字段。第三个字段将自动填写。

【问题讨论】:

  • 如果ratequantity 已经分别是502 但用户在Price 中输入150 怎么办?我们如何更新其他 2 列?将ratequantity 分别更新为503 还是分别更新为350?还是1510?你的问题其实有点不清楚。在Binding 的上下文中,这甚至变得更加复杂。

标签: c# sql winforms datagridview


【解决方案1】:

这是适合您的解决方案。

double s = Convert.ToDouble(DataGridShowAddedProducts.Rows[0].Cells[2].Value);
        double s1 = Convert.ToDouble(DataGridShowAddedProducts.Rows[0].Cells[2].Value);
        double s13 = s1 * s;
        MessageBox.Show(s13.ToString());

【讨论】:

    【解决方案2】:

    处理您的gridview 的CellEndEdit 事件。并在这种情况下计算并将值分配给第三列

    类似

    private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int quantity,rate;
            if (int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value.ToString(), out quantity) && int.TryParse(dataGridView1.Rows[e.RowIndex].Cells["rate"].Value.ToString(), out rate))
            {
                int price = quantity * rate;
                dataGridView1.Rows[e.RowIndex].Cells["price"].Value = price.ToString();
             }
        }
    

    【讨论】:

    • @AnimeshGhosh 同上。您只需要添加一个 if 语句来检查哪些 2 列具有值,并根据该值将值分配给第三列。
    • private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e) { int quantity,rate; for (int i = 0; i
    • 所有行数据输入后是否要执行乘法运算或逐个单元格
    • @AnimeshGhosh 在问题中发布您的代码并提及提供对象引用的行。
    猜你喜欢
    • 1970-01-01
    • 2011-09-25
    • 2017-08-27
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多