C#winform实现在datagridview中输入数据并计算
1、在winform中把要实现的功能界面先做好,这里,我希望通过输入重量来计算出总金额。
2、编写基本数据抓取的代码
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && textBox1.Text != "")
{
show_data(dataGridView1);
//dataGridView1.AllowUserToAddRows = false;//關閉dataGridview中最後一個空白行。
}
else
{
}
}
3、用datagridview中单元格编辑完成的事件去做实现数据的变更和后续动作。
4、编写单元格编辑完成后的事件代码
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[10].Value.ToString()) > 0)
{
float m = float.Parse(this.dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString());
float l = float.Parse(this.dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString());
int n = int.Parse(this.dataGridView1.Rows[e.RowIndex].Cells[10].Value.ToString());
string a = ((m * n)+(l*n)).ToString();
this.dataGridView1.Rows[e.RowIndex].Cells[11].Value = a;
}
}
}
else
{
}
}
5、注意重点行号一定是要用 e.RowIndex来表示,这样才会循环到最后一行,否则会报错。
6、测试输入重量根据设定的公式显示总金额,目的达到。