代码之家  ›  专栏  ›  技术社区  ›  Joey Arnanzo

如何在任何datagridview单元格更新时触发计算

  •  0
  • Joey Arnanzo  · 技术社区  · 6 年前

    我创建了这个计算,当点击一个按钮时触发,它将乘以2个datagridview列,并以三分之一的形式显示结果,然后将2列的总数相加,并将结果发送到2个文本框中

    现在我想在datagridview中输入或编辑一个值(其中一列是product quantity)时实现这一点,所以当输入时,它应该重新计算。。。那么,我应该将此代码添加到哪个空白处?

    private void btnClearPN_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            decimal a = Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
            decimal b = Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value);
    
            decimal c = a * b;
    
            dataGridView1.Rows[i].Cells[4].Value = c.ToString();
    
    
        }
        GrandTotal();
        Qty();
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   JayV    6 年前

    第一个选项-用户完成编辑后更新单元格值

    你应该处理这个问题 CellEndEdit 如果用户完成编辑值后要更新DataGridView,则为DataGridView的事件(这由用户移动到窗体上的下一个单元格或移动到另一个控件决定)。提到 MSDN - DataGridView.CellEndEdit Event 了解更多信息。

    在当前选定单元格的编辑模式停止时发生。

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs dataGridViewCellEventArgs)
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                decimal a = Convert.ToDecimal(dataGridView1.Rows[i].Cells[2].Value);
                decimal b = Convert.ToDecimal(dataGridView1.Rows[i].Cells[3].Value);
    
                decimal c = a * b;
    
                dataGridView1.Rows[i].Cells[4].Value = c.ToString();
            }
    
            GrandTotal();
            Qty();
        }
    

    第二个选项-在用户键入时更新单元格值

    使用这种方法有点复杂,需要正确处理 EditControlShowing 事件和 TextBox 是的 TextChanged 事件

    你应该处理这个问题 编辑控制显示 如果要在用户键入时更新DataGridView,则为DataGridView的事件。此事件将允许您访问编辑控件。对于简单的DataGridView设置,这是一个文本框。尽管这很容易成为一个组合框、复选框或任何数量的其他控件。

    提到 MSDN - DataGridView.EditingControlShowing Event 了解更多信息。

    在显示用于编辑单元格的控件时发生。。

        private DataGridViewRow CurrentRow;
        private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs dataGridViewEditingControlShowingEventArgs)
        {
            CurrentRow = dataGridView1.CurrentRow;
            TextBox textBox = dataGridViewEditingControlShowingEventArgs.Control as TextBox;
            if (textBox != null)
            {
                textBox.TextChanged -= textBox_TextChanged;
                textBox.TextChanged += textBox_TextChanged;
            }
        }
    
        private void textBox_TextChanged(object sender, EventArgs eventArgs)
        {
            TextBox textBox = (TextBox)sender;
            decimal a = Convert.ToDecimal(CurrentRow.Cells[2].Value);
            decimal b = Convert.ToDecimal(CurrentRow.Cells[3].Value);
    
            decimal c = a * b;
    
            CurrentRow.Cells[4].Value = c.ToString();
        }
    

    注: 你必须包括以下几行:

    textBox.TextChanged -= textBox_TextChanged;
    

    由于处理程序是在运行时添加的,因此每次显示编辑控件时,都需要删除之前添加的任何处理程序,否则会多次调用它。