在GridView中使用Session,在.NET中使用ASP#

时间:2014-11-13 09:48:35

标签: c# asp.net session gridview

我想获取所选行的Candidate_id(主键)。并使用session将值传递给其他Web表单 ASP代码


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Candidate_id" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
        <Columns>
            <asp:BoundField DataField="Candidate_id" HeaderText="Candidate_id" ReadOnly="True" SortExpression="Candidate_id" />
            <asp:BoundField DataField="Candidate_Name" HeaderText="Candidate_Name" SortExpression="Candidate_Name" />
            <asp:BoundField DataField="ContactNumber" HeaderText="ContactNumber" SortExpression="ContactNumber" />
            <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
            <asp:HyperLinkField DataNavigateUrlFields="Candidate_id" DataNavigateUrlFormatString="EditCandidate.aspx?Candidate_id=[0]" DataTextField="Candidate_id" HeaderText="Edit" />

        </Columns>
    </asp:GridView>

C#CODE


protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["id"] = GridView1.SelectedRow.Cells[0].Text.ToString();

            Response.Redirect("~/EditCandidate.aspx");
        }

如何在其他页面中访问会话[&#34; id&#34;]? 我试图访问Session["id"]但仍然为空。请帮忙!


另一页的C#代码

 protected void Page_Load(object sender, EventArgs e)
        {
              TextBox3.Text = (String)Session["id"];
        }

2 个答案:

答案 0 :(得分:0)

我认为你应该验证你的web.Config是如何配置的,并验证你的页面是如何配置的。查看此文档:

System.web Pages EnableSessionState

System.web SessionState

EnableSessionState

答案 1 :(得分:0)

请验证应用程序web.config中的会话模式并指定选项

<sessionState mode="Off|InProc|StateServer|SQLServer"
          cookieless="true|false"
          timeout="number of minutes"
          stateConnectionString="tcpip=server:port"
          sqlConnectionString="sql connection string"
          stateNetworkTimeout="number of seconds"/>

timeout - 指定会话在被放弃之前可以空闲的分钟数。默认值为20.

来源:SessionSate

另外在你的上一个片段中使用check ispostback,它的良好编程习惯确保页面第一次加载(没有回发)

 protected void Page_Load(object sender, EventArgs e)
        {
             if(!isPostBack){
              TextBox3.Text = (String)Session["id"].ToString(); }
        }