[英]How to Trigger DataGridView CellEndEdit When A Cell Value Changes Programmatically
[英]How to trigger a calculation when any datagridview cell gets updated
我已经创建了要在单击按钮时触发的计算,它将乘以2个datagridview列并在第三个列中显示结果,然后将2列的总和求和并将结果发送到2个文本框中
现在,无论何时将值输入到datagridview或对其进行编辑(列之一是产品数量),我都想实现这一点,因此在输入值时应重做计算...因此应将此代码添加到哪个void中?
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();
}
第一个选项-用户完成编辑后更新单元格值
如果要在用户完成值编辑后更新DataGridView,则应该处理DataGridView的CellEndEdit
事件(这由用户移至下一个单元格或移至表单上的另一个控件来确定)。 有关更多信息,请参考MSDN-DataGridView.CellEndEdit事件 。
在当前所选单元格的编辑模式停止时发生。
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的EditControlShowing
事件。 此事件将使您可以访问编辑控件。 对于简单的DataGridView设置,这是一个TextBox。 尽管这很容易是ComboBox,CheckBox或任何其他控件。
有关更多信息,请参考MSDN-DataGridView.EditingControlShowing事件 。
在显示用于编辑单元格的控件时发生。
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;
随着在运行时添加处理程序,每次显示“编辑控件”时,都必须删除任何以前添加的处理程序,否则它将被多次调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.