0

我只是想将单选按钮列表的 SelectedIndex 放入 OnSelectedIndexChanged 事件的 int 数组中。我尝试了以下代码但不起作用:

我做了一个这样的数组:

int[] correctAnswers = { -1, -1, -1, -1, -1 }; and i tried this as well:     
int[] correctAnswers = new int[100];

//SelectionChangeEvent    
protected void rbAnswers_SelectedIndexChanged(object sender, EventArgs e)    
{               
    int j = rbAnswers.SelectedIndex;                
    correctAnswers.SetValue(j, i); //or correctAnswers[i] = j;        
}

我正在.Net 中制作一个在线测试系统。我正在更改标签中的问题和 RadioButtonList 中的答案。值来自数据库。我正在动态更改 RadioButtonList 但是如果我选择一个答案并单击下一个按钮,然后按上一个按钮返回,我的选择就会消失。所以为此我有一个逻辑是将选定的索引存储在一个 int 数组中,然后在下一个和上一个按钮调用该索引值并放入 RadioButtonList 的 SelectedIndex 中。所以请帮助我,我怎样才能在 OnSelectionChange 的 int 数组中获取这个选定的值?还有一个补充是我使 RadioButtonList 的 Post Back True。

4

2 回答 2

1

如果您要动态填充控件,我可以收集到您的信息,您将需要考虑如何在“用户旅程”中保持值。如果所有内容都在一个页面上计算,您可以使用ViewState来持久化信息。在 aControl中,例如 aPageUserControl您可以执行以下操作:

/// <summary>
/// Gets or sets the answers to the view state
/// </summary>
private List<int> Answers
{
    get
    {
        // attempt to load the answers from the view state
        var viewStateAnswers = ViewState["Answers"];

        // if the answers are null, or not a list, create a new list and save to viewstate
        if (viewStateAnswers  == null || !(viewStateAnswers  is List<int>))
        {
            Answers = new List<int>();
        }

        // return the answers list
        return (List<int>)viewStateAnswers;
    }
    set
    {
        // saves a list to the view state
        var viewStateAnswers = ViewState["Answers"];
    }
}
于 2012-03-27T16:19:10.907 回答
0

我相信您正在实例化每个页面加载/ posctback 数组的新实例的问题,所有页面变量在页面卸载发生后都会消失。因此,每次触发按钮单击事件时,您都会收到回发 - 创建页面类的新实例,并且所有基础字段也被实例化。

显然您必须缓存中间结果,对于如此少量的数据(很少的项目数组)您可以考虑使用 session. 还要考虑使用泛型List<>而不是数组,尤其是在存储导致装箱/拆箱的值类型时。

class MyPage: Page
{
    private IList<int> correctAnswers;
    private readonly string cacheKey = "cachedResults";

    protected void Page_Load(object sender, EventARgs args)
    {
       this.LoadCache();
    }

    protected void rbAnswers_SelectedIndexChanged(object sender, EventArgs e)    
    {               
        if (rbAnswers.SelectedIndex >= 0)
        {
           // TODO: ensure there are enough allocated items
           // so indexer [] would not throw
           correctAnswers[rbAnswers.SelectedIndex] = i; 
           this.SyncCache();
        }
    }

    private LoadCache()
    {
       var resultsCache = Session[this.cacheKey];
       if (resultsCache != null)
       {
          this.correctAnswers = resultsCache as List<int>;
       }
    }

    private void SyncCache()
    {
        Session[this.cacheKey] = this.correctAnswers;
    }  
}
于 2012-03-27T16:14:39.330 回答