从TextBox更新数据库及DataGridView的技术实现问询
Alright, let's break down exactly how to build that save functionality for your app—since you already have the display and edit toggle working, this is just tying the final pieces together. I’ll assume you’re working with WinForms (given the DataGridView/TextBox controls) and walk through the solution step by step:
Core Idea
When the user clicks Save, we need to:
- Pull the updated values from your top-panel controls (TextBox, ComboBox, etc.)
- Validate the data (optional but highly recommended)
- Update the corresponding record in your database
- Refresh the DataGridView to show the latest changes
Step-by-Step Implementation
1. Grab the Selected Row's Unique Identifier
First, you need to know which record to update. Get the primary key (like ID, OrderID) from the highlighted DataGridView row—this is your database’s "target" for the update.
Example if you’re using a DataTable as the DataGridView’s source:
// Make sure a row is actually selected first! if (dataGridView1.SelectedRows.Count == 0) { MessageBox.Show("Please select a row to update first."); return; } DataGridViewRow selectedRow = dataGridView1.SelectedRows[0]; int recordId = Convert.ToInt32(selectedRow.Cells["ID"].Value); // Replace "ID" with your PK column name
2. Collect Updated Values from Controls
Pull the new data from your top-panel inputs:
string updatedName = textBox_Name.Text.Trim(); string updatedStatus = comboBox_Status.SelectedItem.ToString(); DateTime updatedDate = dateTimePicker_DueDate.Value; // Add more lines for all your input controls
3. Validate the Data (Don’t Skip This!)
Quick checks to avoid saving garbage data to your database:
if (string.IsNullOrEmpty(updatedName)) { MessageBox.Show("Name can’t be empty!"); textBox_Name.Focus(); return; } // Add other rules—like checking if a date is in the future, or a number is valid
4. Update the Database
Choose the approach that fits your current setup:
Option A: ADO.NET (Raw SQL)
If you’re writing direct SQL queries (use parameters to prevent SQL injection!):
string connectionString = "YOUR_DATABASE_CONNECTION_STRING"; string updateQuery = @" UPDATE YourTableName SET Name = @Name, Status = @Status, DueDate = @DueDate WHERE ID = @RecordID"; try { using (SqlConnection conn = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(updateQuery, conn)) { // Add parameters cmd.Parameters.AddWithValue("@Name", updatedName); cmd.Parameters.AddWithValue("@Status", updatedStatus); cmd.Parameters.AddWithValue("@DueDate", updatedDate); cmd.Parameters.AddWithValue("@RecordID", recordId); conn.Open(); int rowsUpdated = cmd.ExecuteNonQuery(); if (rowsUpdated > 0) MessageBox.Show("Data saved successfully!"); else MessageBox.Show("No record found to update."); } } } catch (Exception ex) { MessageBox.Show($"Save failed: {ex.Message}"); }
Option B: Entity Framework (EF)
If you’re using EF for data access, the code is cleaner:
try { using (var dbContext = new YourDbContext()) { var targetRecord = dbContext.YourTable.Find(recordId); if (targetRecord != null) { // Update the entity’s properties targetRecord.Name = updatedName; targetRecord.Status = updatedStatus; targetRecord.DueDate = updatedDate; dbContext.SaveChanges(); MessageBox.Show("Data saved successfully!"); } else { MessageBox.Show("No record found to update."); } } } catch (Exception ex) { MessageBox.Show($"Save failed: {ex.Message}"); }
5. Refresh the DataGridView
Once the database is updated, make sure the grid shows the new values. Pick the method that works best for you:
Option 1: Rebind the Data Source (Simple, but re-queries the whole table)
// Re-fetch data from your database (use your existing data load method) DataTable freshData = LoadDataFromDatabase(); dataGridView1.DataSource = freshData;
Option 2: Update the Selected Row Directly (Faster, no re-query)
Skip reloading the whole dataset and just update the cells in the selected row:
selectedRow.Cells["Name"].Value = updatedName; selectedRow.Cells["Status"].Value = updatedStatus; selectedRow.Cells["DueDate"].Value = updatedDate;
Option 3: Use BindingSource (Cleanest if you’re already using one)
If your DataGridView is bound to a BindingSource, just reset the bindings:
// Assume bindingSource1 is your DataGridView’s data source bindingSource1.ResetBindings(false);
Extra Tips
- Reset Edit State: After saving, set your TextBox/ComboBox back to read-only mode to match your edit button’s behavior.
- Concurrency: If multiple users might edit the same record, add a
Versioncolumn to your database table (for optimistic locking) to avoid overwriting changes. - Error Handling: Always wrap database code in
try-catchblocks to handle connection issues or invalid data gracefully.
内容的提问来源于stack exchange,提问作者Darrell

