2017-06-21 105 views
1

我想保存单选按钮状态并在重新加载页面时再次选择单选按钮。我写了下面的代码,但它不工作:保存单选按钮状态

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

public partial class Question_1 : System.Web.UI.Page 
{ 
    public int index; 
    public bool flag = false; 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if(flag) 
     { 
      index = (int)Session["index"]; 
      if (index == 5) 
      { 
       totallyagree.Checked = true; 
      } 
      else if (index == 4) 
      { 
       agree.Checked = true; 
      } 
     } 
    } 
    protected void next_Click(object sender, EventArgs e) 
    { 
     flag=true; 
     if (totallyagree.Checked) 
     { 
      Session["index"] = 5; 
     } 
     else if (agree.Checked) 
     { 
      Session["index"] = 4; 
     } 
     Response.Redirect("Question 2.aspx"); 
    } 
    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     //Session["index"] = RadioButtonList1.SelectedIndex; 
    } 
} 

请帮我解决这个问题。

回答

0

你试过IsPostBack吗?

protected void Page_Load(object sender, EventArgs e) 
{ 
    if(!IsPostBack) 
    { 
     index = (int)Session["index"]; 
     if (index == 5) 
     { 
      totallyagree.Checked = true; 
     } 
     else if (index == 4) 
     { 
      agree.Checked = true; 
     } 
    } 
} 
+0

使用IsPostBack给出空引用异常,这就是为什么我使用了一个标志变量,但问题是单选按钮状态不存储。 –