2011-03-20 64 views
0

我想從asp.net嚮導添加表單數據到會話數組對象。對象應該存儲用戶爲每個問題選擇的問題編號和問題答案。我試圖使用多維數組來存儲問題編號和相關的答案。我也會開放使用散列表或字典解決方案。c#session多維數組

這是代碼我有到目前爲止:

string[,] strQandA = new string[10, 2] {{"1", Q1.SelectedValue}, {"2", Q2.SelectedValue}, {"3", Q3.SelectedValue}, {"4", Q4.SelectedValue}, {"5", Q5.SelectedValue}, {"6", Q6.SelectedValue}, {"7", Q7.SelectedValue}, {"8", Q8.SelectedValue}, {"9", Q9.SelectedValue}, {"10", Q10.SelectedValue}}; 
Session["mySession"] = strQandA; 

這是正確的嗎?任何幫助,將不勝感激。謝謝

+1

「這是正確的嗎?」 ==「你試過了嗎?它有效嗎?」 – 2011-03-20 21:57:22

+0

我試過Response.Write(Session [「mySession」]);並返回System.String [,]。 – multiv123 2011-03-20 22:05:27

+1

這是因爲當你調用'Write'時,它會在你傳遞它的對象上調用'ToString()',如果它不是一個字符串的話。如果你在一個沒有超載的ref類型上調用'ToString()',它會默認寫出Type。您需要將數組索引到數組中以獲取值。 – 2011-03-20 22:18:31

回答

1

您的需求的更好的做法是以問題編號爲關鍵字並選擇值作爲值的字典。類似於:

DropDownList[] arrDDL = new DropDownList[] { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10 }; 
Dictionary<int, string> strQandA = new Dictionary<int, string>(); 
for (int i = 0; i < arrDDL.Length; i++) 
    strQandA.Add(i + 1, arrDDL[i].SelectedValue); 
Session["mySession"] = strQandA; 

要稍後訪問特定值,例如第三個問題的答案:

(Session["mySession"] as Dictionary<int, string>)[3] 
0

您需要在對象上強制轉換集合,Response.Write調用ToString()並返回默認實現。

Dictionary<string, YourType> strQandA = new Dictionary<string, YourType>(); 
Session["mySession"] = strQandA; 

Dictionary<string, YourType> mySession = (Dictionary<string, YourType>)Session["mySession"];