You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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

  1. Get the parent GridView row from the button – this lets you access the TextBoxes in that specific row.
  2. Retrieve the row ID from the button's CommandArgument (you already set this in your markup, great job!).
  3. Locate the TextBox controls in the row to pull the updated score values.
  4. Validate input (optional but recommended) to ensure scores are valid numbers before sending to the database.
  5. Use a parameterized update query to avoid SQL injection and safely update the database.
  6. 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 YourConnectionString with the name of your connection string in web.config, and YourTableName with your actual database table name.
  • Input Validation: Adjust the TryParse data type to match your database columns (e.g., int.TryParse if scores are integers).
  • Error Handling: Add try-catch blocks 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:38:04