使用 window 表单的 C# 编程
C# programming with window forms
private void dataGridView1_RowHeaderMouseClick_1(object sender, DataGridViewCellMouseEventArgs e)
{
int ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txtName.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txtFname.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txtAddress.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Update student set name ='"+txtName.Text+"', fathername= '"+txtFname.Text+"', address= '"+txtAddress.Text+"' where id = ID", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Display();
MessageBox.Show("Record is Updated");
当我 运行 这段代码时,我的整个数据库 table 都会更新为当前值,我无法理解这个问题
"where id = ID" 条件始终为真,因此所有记录都会受到影响。您需要为 "ID" 实际设置一个值。也许你需要写
"where id =" + ID.ToString()
private void dataGridView1_RowHeaderMouseClick_1(object sender, DataGridViewCellMouseEventArgs e)
{
int ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txtName.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txtFname.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txtAddress.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
private void btnEdit_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Update student set name ='"+txtName.Text+"', fathername= '"+txtFname.Text+"', address= '"+txtAddress.Text+"' where id = ID", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Display();
MessageBox.Show("Record is Updated");
当我 运行 这段代码时,我的整个数据库 table 都会更新为当前值,我无法理解这个问题
"where id = ID" 条件始终为真,因此所有记录都会受到影响。您需要为 "ID" 实际设置一个值。也许你需要写
"where id =" + ID.ToString()