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

ASP.NET GridView 編輯報 NullReferenceException:Session/Application 為 null 時 ToString() 崩潰、防禦性編程修正

     編輯:程式設計綜合問答

錯誤堆疊


Label2.Text = Session["UserID"].ToString(); // Session["UserID"] 為 null → NRE
Label2.Text = Application["count"].ToString(); // 同理

根因

  • 應用程式池回收、Session 逾時、用戶首次訪問 → Session/Application 內鍵值為 null。
  • 直接呼叫 .ToString() 拋出 NullReferenceException。

修正代碼 (防禦性檢查)


protected void Page_Load(object sender, EventArgs e) {
    if (Application["count"] != null)
        Label2.Text = "當前在線人數為 " + Application["count"].ToString() + "人";

    if (Session["UserID"] != null)
        Label2.Text = Session["UserID"].ToString(); // 注意:此行會覆蓋上一行,建議用不同 Label

    if (!IsPostBack) this.bind();
}

進階:安全擴充方法


public static class SessionExtensions {
    public static string GetString(this HttpSessionState session, string key, string defaultValue = "") {
        return session[key]?.ToString() ?? defaultValue;
    }
    public static int GetInt(this HttpSessionState session, string key, int defaultValue = 0) {
        return session[key] != null ? Convert.ToInt32(session[key]) : defaultValue;
    }
}

// 使用
Label2.Text = Session.GetString("UserID", "Guest");
int count = Application.GetInt("count");

GridView 編輯/更新其他潛在問題

  • GridView1.Rows[e.RowIndex].Cells[2].Controls[0] 假設為 TextBox,若模板不同會失敗 → 建議 FindControl("txtName")。
  • SQL 字串拼接存在 **SQL 注入風險**,必須使用參數化查詢:
    cmd.Parameters.AddWithValue("@name", cname);
  • Button_send_Click 中 TextBox1.Text = " " 應為 string.Empty 或 ""。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved