DataGridView更新按钮失效,数据库未同步更新问题求助
Hey there! Let's walk through why your update button isn't saving changes to the database, and fix it step by step. I'll break down the key problems in your code and show you how to adjust things.
Key Issues in Your Current Code
- You never execute the update command: Your code sets up the
SqlCommandand parameters, but you don't callcmd.ExecuteNonQuery()to send the update to the database. That's why you see a success message but no actual changes! - No connection cleanup: You open a database connection but never close it. This can lead to connection leaks over time.
- Broken WHERE clause if you modify the RFID number: Your update query uses the new RFID number (from
textBox1) in theWHEREclause. If the user changes the RFID, the query won't find the original record to update. - You're not refreshing the original Records form: Even if the update worked, you're opening a new instance of
Recordsinstead of refreshing the existing one—so you won't see the updated data.
Step-by-Step Fixes
1. Pass the Original RFID Number to UpdateRecords
First, we need to keep track of the original RFID number (before any edits) to correctly target the record in the database. Add a public property to your UpdateRecords form:
// Inside UpdateRecords.cs public string OriginalRfidNo { get; set; }
Then modify the button click in your main Records form to pass this original value:
private void button2_Click(object sender, EventArgs e) { UpdateRecords obj = new UpdateRecords(); // Save the original RFID to use as our update condition obj.OriginalRfidNo = dataGridView1.CurrentRow.Cells[1].Value.ToString(); // Populate the form fields as before obj.textBox1.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString(); obj.textBox2.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString(); obj.textBox3.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString(); obj.textBox4.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString(); obj.comboBox1.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString(); obj.textBox6.Text = dataGridView1.CurrentRow.Cells[6].Value.ToString(); obj.textBox7.Text = dataGridView1.CurrentRow.Cells[7].Value.ToString(); obj.comboBox2.Text = dataGridView1.CurrentRow.Cells[8].Value.ToString(); obj.textBox9.Text = dataGridView1.CurrentRow.Cells[9].Value.ToString(); obj.comboBox3.Text = dataGridView1.CurrentRow.Cells[10].Value.ToString(); obj.ShowDialog(); // After UpdateRecords closes, refresh the DataGridView to show changes LoadStudentData(); // We'll create this method next! }
2. Fix the Update Command in UpdateRecords
Rewrite the save button code to execute the command, clean up connections, and use the original RFID for the WHERE clause:
private void button1_Click(object sender, EventArgs e) { // Use 'using' to automatically close the connection when done using (SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-EB4EK81\SQLEXPRESS; Initial Catalog=TACLC; Integrated Security=True")) { // Update query uses original RFID to find the record, allows changing the RFID if needed string updateQuery = @"UPDATE tbl_registerStudent SET rfidno = @newRfidno, lastname = @lastname, firstname = @firstname, middlename = @middlename, gender = @gender, address = @address, contactno = @contactno, gradelevel = @gradelevel, year = @year, section = @section WHERE rfidno = @originalRfidno"; SqlCommand cmd = new SqlCommand(updateQuery, con); // Add parameters (separate original and new RFID) cmd.Parameters.AddWithValue("@originalRfidno", OriginalRfidNo); cmd.Parameters.AddWithValue("@newRfidno", textBox1.Text); cmd.Parameters.AddWithValue("@lastname", textBox2.Text); cmd.Parameters.AddWithValue("@firstname", textBox3.Text); cmd.Parameters.AddWithValue("@middlename", textBox4.Text); cmd.Parameters.AddWithValue("@gender", comboBox1.Text); cmd.Parameters.AddWithValue("@address", textBox6.Text); cmd.Parameters.AddWithValue("@contactno", textBox7.Text); cmd.Parameters.AddWithValue("@gradelevel", comboBox2.Text); cmd.Parameters.AddWithValue("@year", textBox9.Text); cmd.Parameters.AddWithValue("@section", comboBox3.Text); try { con.Open(); // Execute the update and check how many rows were changed int rowsUpdated = cmd.ExecuteNonQuery(); if (rowsUpdated > 0) { MessageBox.Show("Update Successfully", "Update Message Prompt", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); // Close the update form to return to Records } else { MessageBox.Show("No record found to update. Check the original RFID.", "Update Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception ex) { // Show actual error message for debugging MessageBox.Show($"Update failed: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
3. Add a Method to Refresh the DataGridView in Records
Create a method in your Records form to reload data from the database and bind it to the DataGridView. This ensures you see the updated data after closing the update form:
private void LoadStudentData() { using (SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-EB4EK81\SQLEXPRESS; Initial Catalog=TACLC; Integrated Security=True")) { string selectQuery = "SELECT * FROM tbl_registerStudent"; SqlDataAdapter da = new SqlDataAdapter(selectQuery, con); DataTable dt = new DataTable(); da.Fill(dt); dataGridView1.DataSource = dt; } }
Call this method when your Records form loads too (add it to the form's Load event) so data is loaded initially.
Why These Changes Work
ExecuteNonQuery()sends the update command to the database and returns how many rows were affected—so you can confirm the update actually happened.- The
usingstatement automatically closes and disposes the database connection, preventing leaks. - Using the original RFID in the
WHEREclause ensures we target the correct record, even if the user edits the RFID value. - Refreshing the existing
Recordsform's DataGridView shows the latest data from the database, instead of opening a new window.
内容的提问来源于stack exchange,提问作者William Gar

