隐藏字段“对象引用未设置为对象实例”时出错。

时间:2016-06-24 21:14:10

标签: c# asp.net

我想向用户显示一条消息,但我在这一行收到错误:

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
Reg_id=@Reg_id order by Reg_id desc End

1 个答案:

答案 0 :(得分:0)

您应该检查会话是否存在,以及会话在分配之前是否具有该密钥。

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