c# dataGridView列相乘
怎写代码在dataGridView里把两列的数相乘等于第三列.即dataGridView里,在列【单价】、【数量】里填数字后,【金额】自动算出来显示。点击保存后把数据插到数据库里。【金额】=【单价】*【数量】
private void button1_Click_1(object sender, EventArgs e)
{
if (dbInsert())
{
MessageBox.Show("新增成功!");
}
}
private Boolean dbInsert()
{
conn = new SqlConnection(@"Data Source=.;Initial Catalog=CS;Persist Security Info=True;User ID=sa;Password=rt");
string strSql = "select [物品名称],[单价],[数量],([单价]*[数量]) AS [金额] from test2 ";
DataTable dtShow = new DataTable();
dtShow = (DataTable)this.dataGridView2.DataSource;
try
{
this.conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
foreach (DataRow dr in dtShow.Rows)
{
strSql =
string.Format(
"INSERT INTO test2 (入仓单编号,经手人,物品名称,单价,数量,金额) values ('{0}','{1}','{2}','{3}','{4}','{5}')",
textBox1.Text.Trim(), textBox2.Text.Trim(), dr["物品名称"], dr["单价"], dr["数量"], dr["金额"]
);
cmd.CommandText = strSql;
cmd.ExecuteNonQuery();
}
this.conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return false;
}
for (int i = 0; i < dataGridView2.ColumnCount; i++)
{
dataGridView2.Columns[i].Width = 84;
}
button2.Enabled = false;
dataGridView2.Columns[0].ReadOnly = true;
//之后添加
[解决办法]
添加dataGridVIew的CurrentCellChanged事件
private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
dataGridView1.CurrentRow.Cells["金额"].Value =Convert.ToInt32(dataGridView1.CurrentRow.Cells["单价"].Value) * Convert.ToInt32(dataGridView1.CurrentRow.Cells["数量"].Value);
}
private void button1_Click(object sender, EventArgs e)
{
//取当前行数据保存
}
[解决办法]
int c = Convert.ToInt16(this.dataGridView2.Rows[0].Cells[2].Value.ToString());
int d = Convert.ToInt16(this.dataGridView2.Rows[0].Cells[3].Value.ToString());
dataGridView2.Rows[0].Cells[4].Value = Convert.ToString(c * d);