首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ASP.NET GridView 資料遍歷存入資料庫失效排查指南

     編輯:程式設計綜合問答

問題現象

GridView 顯示資料正常,但 foreach (GridViewRow dr in GridView2.Rows) 遍歷寫入 SQL Server 時,資料庫無新增記錄,無報錯。

常見原因排查清單

  1. GridView 未綁定資料或已重新綁定
    確認 GridView2.DataBind() 僅在 !IsPostBack 執行,PostBack 時未清空資料源導致 Rows 為空。
  2. FindControl 找不到控制項
    Label3 若在 TemplateField 中,需確認 dr.FindControl("Label3") 非 null,建議加斷點檢查。
  3. SQL 執行未提交/連線問題
    檢查 db.Insert() 內部 ExecuteNonQuery() 返回值,若為 -1 表示失敗。確認連線字串、權限、表結構一致。
  4. 隱式轉換錯誤
    int.Parse(((Label)dr.FindControl("Label3")).Text) 若 Text 為空或非數字會拋出異常,需 TryParse 防禦。

參考代碼:參數化查詢 + 事務 + 錯誤處理

using (var conn = new SqlConnection(connStr))
using (var cmd = conn.CreateCommand()) {
    conn.Open();
    var tran = conn.BeginTransaction();
    cmd.Transaction = tran;
    try {
        foreach (GridViewRow row in GridView2.Rows) {
            if (row.RowType != DataControlRowType.DataRow) continue;
            var lbl = row.FindControl("Label3") as Label;
            if (lbl == null || !int.TryParse(lbl.Text, out int typeId)) continue;

            cmd.CommandText = @"INSERT INTO testdetail (examinationid, typekind, typeid, score)
                                VALUES (@examId, '單選題', @typeId, @score)";
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@examId", afterID);
            cmd.Parameters.AddWithValue("@typeId", typeId);
            cmd.Parameters.AddWithValue("@score", int.Parse(txtSingleFen.Text));
            cmd.ExecuteNonQuery();
        }
        tran.Commit();
    } catch (Exception ex) {
        tran.Rollback();
        // 記錄日誌 / 顯示錯誤
    }
}

核心改進點

  • 參數化查詢:防 SQL 注入、解決型別轉換、提升效能。
  • 事務包裹:保證全成功或全失敗,資料一致性。
  • 資源釋放:using 確保連線關閉。
  • 防禦性編程:TryParse、null 檢查、RowType 過濾。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved