2016-06-24 49 views
-1

我想顯示一條消息給用戶,但我在這條線得到一個錯誤:錯誤的隱藏字段「對象引用不設置到對象的實例。」

HF_Reg_Id.Value = Session["Reg_id"].ToString(); 

其中HF_Reg_Id是一個隱藏的領域。

標記:

<asp:GridView ID="GV_Contact" runat="server" DataKeyNames="Contact_id" AutoGenerateColumns="False"AllowPaging="True"AllowSorting="True"> 
    <AlternatingRowStyle CssClass="alt"></AlternatingRowStyle> 
    <Columns> 
      <asp:BoundField DataField="Contact_id" HeaderText="ID" /> 
      <asp:BoundField DataField="Reg_id" HeaderText="Register ID" /> 
      <asp:BoundField DataField="txtName" HeaderText="Name" /> 
      <asp:BoundField DataField="Email" HeaderText="Email" /> 
      <asp:BoundField DataField="txtBody" HeaderText="Message" /> 
      <asp:BoundField DataField="MsgType" HeaderText="Message Type" /> 
    </Columns> 
</asp:GridView> 

代碼背後:

protected void Page_Load(object sender, EventArgs e) 
    { 
     HF_Reg_Id.Value = Session["Reg_id"].ToString(); 
     BindGrid1(); 
    } 
    public DataSet viewContactMsg() 
    { 
     SqlConnection con = new SqlConnection(conString); 
     SqlCommand cmd = new SqlCommand(); 

     cmd.CommandText = "Set_Field_User_Msg"; 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.Add("@Reg_id", HF_Reg_Id.Value); 
     cmd.Connection = con; 

     SqlDataAdapter ad = new SqlDataAdapter(); 
     DataSet ds = new DataSet(); 
     ad.SelectCommand = cmd; 
     ad.Fill(ds); 

     return ds; 
    } 
    public void BindGrid1() 
    { 
     DataSet ds = viewContactMsg(); 

     GV_Contact.DataSource = ds; 
     GV_Contact.DataBind(); 
    } 

create PROC Set_Field_User_Msg @Reg_id as int As Begin Select 
Contact_id,Reg_id,Email,txtName,txtBody,MsgType from Contact where 
[email protected]_id order by Reg_id desc End 
+0

歡迎來到Stack Overflow。請在標題中總結您的問題,並在正文中添加您的描述性問題。 –

+0

什麼行會拋出錯誤?有幾個引用HF_Reg_Id,我認爲是你的隱藏領域。另外,如果錯誤與隱藏域有關,爲什麼還要向我們展示GridView的標記? –

+0

你確定你的會議正在進行價值嗎? – Kramb

回答

0

您應該檢查是否存在會話,如果會話具有分配給它之前的關鍵。

if(Session != null && Session["Reg_id"] != null) 
{ 
    HF_Reg_Id.Value = Session["Reg_id"].ToString(); 
} 
相關問題