如何从GridView的TextBox取值并实现对应行数据库更新?
Complete Implementation for GridView Row Update
You're already off to a solid start by capturing the clicked button and setting the CommandArgument to the row's unique ID. Here's how to finish the logic to safely update your database with the new score values:
Step-by-Step Breakdown
- Get the parent GridView row from the button – this lets you access the TextBoxes in that specific row.
- Retrieve the row ID from the button's
CommandArgument(you already set this in your markup, great job!). - Locate the TextBox controls in the row to pull the updated score values.
- Validate input (optional but recommended) to ensure scores are valid numbers before sending to the database.
- Use a parameterized update query to avoid SQL injection and safely update the database.
- Rebind the GridView to immediately reflect the changes for the user.
Updated C# Code
protected void btnUpdate_Click(object sender, EventArgs e) { // Get the clicked button instance Button myUpdateButton = (Button)sender; // Get the parent GridView row that contains this button GridViewRow row = (GridViewRow)myUpdateButton.NamingContainer; // Convert the CommandArgument to your ID data type (adjust if your ID is a string) int rowId = Convert.ToInt32(myUpdateButton.CommandArgument); // Find the TextBox controls in the current row TextBox txtSignificance = (TextBox)row.FindControl("txtSignificanceScore"); TextBox txtInnovation = (TextBox)row.FindControl("txtInnovationScore"); // Validate that scores are valid numbers (adjust data type if needed: int, float, etc.) if (!decimal.TryParse(txtSignificance.Text, out decimal significanceScore) || !decimal.TryParse(txtInnovation.Text, out decimal innovationScore)) { // Show user feedback for invalid input ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please enter valid numeric scores!');", true); return; } // Perform database update with parameterized query (replace with your DB setup) string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString; using (SqlConnection conn = new SqlConnection(connectionString)) { string updateQuery = @"UPDATE YourTableName SET significanceScore = @SignificanceScore, innovationScore = @InnovationScore WHERE id = @Id"; using (SqlCommand cmd = new SqlCommand(updateQuery, conn)) { // Add parameters to prevent SQL injection cmd.Parameters.AddWithValue("@SignificanceScore", significanceScore); cmd.Parameters.AddWithValue("@InnovationScore", innovationScore); cmd.Parameters.AddWithValue("@Id", rowId); conn.Open(); int rowsAffected = cmd.ExecuteNonQuery(); conn.Close(); // Update UI based on success/failure if (rowsAffected > 0) { // Rebind GridView to show fresh data BindGridView(); ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Row updated successfully!');", true); } else { ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Failed to update row – ID may not exist!');", true); } } } } // Helper method to centralize GridView binding logic private void BindGridView() { // Replace this with your existing code to fetch the dataset DataSet dsResult = GetYourDatasetFromDatabase(); // Your method to retrieve data dgAbstractSummary.DataSource = dsResult; dgAbstractSummary.DataBind(); }
Key Notes
- Replace placeholders: Swap
YourConnectionStringwith the name of your connection string inweb.config, andYourTableNamewith your actual database table name. - Input Validation: Adjust the
TryParsedata type to match your database columns (e.g.,int.TryParseif scores are integers). - Error Handling: Add
try-catchblocks around the database code to handle exceptions like connection failures gracefully. - Parameterized Queries: Never concatenate user input into SQL strings – parameters are critical for security and reliability.
内容的提问来源于stack exchange,提问作者Mohammad Shahbaz
相关产品推荐
相关产品推荐

