C#winform实现在datagridview中输入数据并计算
的有关信息介绍如下:
在winform开发过程中,需要对datagridview中查询出来的数据进行计算,也就是说,我们在其中一个栏位中输入数据,将会使指定的单元格数据也发生变化,下面,我们就一起来看看,怎么实现输入重量,根据原有的单价和数量算出总金额。
在winform中把要实现的功能界面先做好,这里,我希望通过输入重量来计算出总金额。
编写基本数据抓取的代码
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && textBox1.Text != "")
{
show_data(dataGridView1);
//dataGridView1.AllowUserToAddRows = false;//關閉dataGridview中最後一個空白行。
}
else
{
}
}
用datagridview中单元格编辑完成的事件去做实现数据的变更和后续动作。
编写单元格编辑完成后的事件代码
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows.Count > 1)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (int.Parse(dataGridView1.Rows[e.RowIndex].Cells.Value.ToString()) > 0)
{
float m = float.Parse(this.dataGridView1.Rows[e.RowIndex].Cells.Value.ToString());
float l = float.Parse(this.dataGridView1.Rows[e.RowIndex].Cells.Value.ToString());
int n = int.Parse(this.dataGridView1.Rows[e.RowIndex].Cells.Value.ToString());
string a = ((m * n)+(l*n)).ToString();
this.dataGridView1.Rows[e.RowIndex].Cells.Value = a;
}
}
}
else
{
}
}
注意重点行号一定是要用e.RowIndex来表示,这样才会循环到最后一行,否则会报错。
测试输入重量根据设定的公式显示总金额,目的达到。



