C# 如何在任何datagridview单元格更新时触发计算
我已经创建了这个计算,当点击一个按钮时触发,它将乘以2个datagridview列,并在第三个列中显示结果,然后将2列的总数相加,并将结果发送到2个文本框中 现在,我想在向datagridview输入值或编辑值(其中一列是product quantity)时实现这一点,因此当输入值时,它应该重做计算。。。那么,我应该将此代码添加到哪个空白处C# 如何在任何datagridview单元格更新时触发计算,c#,datagridview,C#,Datagridview,我已经创建了这个计算,当点击一个按钮时触发,它将乘以2个datagridview列,并在第三个列中显示结果,然后将2列的总数相加,并将结果发送到2个文本框中 现在,我想在向datagridview输入值或编辑值(其中一列是product quantity)时实现这一点,因此当输入值时,它应该重做计算。。。那么,我应该将此代码添加到哪个空白处 private void btnClearPN_Click(object sender, EventArgs e) { for (int i = 0
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();
}
private void btnClearPN\u单击(对象发送方,事件参数e)
{
对于(int i=0;i
第一个选项-在用户完成编辑后更新单元格值
如果要在用户编辑完值后更新DataGridView,则应处理DataGridView的CellEndEdit
事件(这由用户移动到下一个单元格或移动到窗体上的另一个控件来确定)。有关更多信息,请参阅
在当前选定单元格的编辑模式停止时发生
注意:必须包括以下行:
textBox.TextChanged -= textBox_TextChanged;
由于处理程序是在运行时添加的,因此每次显示编辑控件时,都必须删除以前添加的任何处理程序,否则它将被多次调用。尝试过了,Jay。。还是不走运。。我应该附加完整的代码吗?请描述它是如何工作的,并注意我已将原始的
Convert.ToInt32
更改为Convert.ToDecimal
,但它不会更改值,除非我单击按钮或单击第三列的单元格,但在编辑后不会更改quantity@JoeyArnanzo如果我理解正确,那么当您离开DataGridView或移动到下一个单元格时,总数会更新吗?您想在用户输入/更改值时更新总数吗?是的,这就是我想要的。非常感谢。
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;