我想擁有一個在兩種不同方法之間共享的對象數組。在不同事件中訪問相同的對象
我的網頁上button1的onclick調用方法1,該方法填充objectArray的所需值。我需要button2的onclick方法能夠使用method1正在處理的相同數據訪問同一個objectArray。
using myWebReference;
{
public partial class _Default : System.Web.UI.Page
{
ObjectArray[] myObjects = new ObjectArray[100];
public void Page_Load(object sender, EventArgs e)
{
//I have nothing in here at the moment
}
public void method1(object sender, EventArgs e)
{
//myObjects[]'s values are calculated and assigned here.
}
public void method2(object sender, EventArgs e)
{
String key = myObjects[0].value;
//when I try to get data within myObjects here, myObjects does exist,
//but it is empty and I get a null reference error when I try to use its values.
}
}
我建議閱讀一些關於asp.net和web的樣本和書籍,一般來說...這裏你有你的頁面類將在每個請求上重新創建,因此myObjects將是空的。每個按鈕點擊都是一個新的請求。您需要將myObjects保存到某個存儲(並在pageLoad或類似事件中恢復),或者將其發送給客戶端,然後在單擊button2時發回服務器。 – Felix