添加控件在Page_Init
,而不是在你的Page_Load
。 [1]
此外,你沒有按照它應該這樣做。考慮以下代碼
//your collection of objects goes here. It might be something different than
//this, but basically a Dictionary<int, YourType> goes fine
public Dictionary<Int32, string> Ids
{
get { return (ViewState["ids"] ?? new Dictionary<Int32, string>()) as Dictionary<Int32, string>; }
set { ViewState["ids"] = new Dictionary<Int32, string>(); }
}
protected void Page_Init(object sender, EventArgs e)
{
//load the data using your DAO
Ids = new Dictionary<int, string>();
Ids.Add(1, "http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg");
Ids.Add(2, "http://helios.gsfc.nasa.gov/image_euv_press.jpg");
foreach (var item in Ids)
{
ImageButton imb = new ImageButton()
{
ImageUrl = item.Value,
CommandArgument = item.Key.ToString(),
CommandName = "open"
};
imb.Click += new ImageClickEventHandler(imb_Click);
PH1.Controls.Add(imb);
}
}
void imb_Click(object sender, ImageClickEventArgs e)
{
Response.Write("You purchased " + Ids[int.Parse(((ImageButton)sender).CommandArgument)]);
}
[1](CTRL + C/Ctrl + V從一些其他的問題,我回答了上週):即必須保持之間的頁面週期應該聲明
一切在Page_Init
,而不是Page_Load
。
所有初始化,如添加事件處理程序和添加控件都應該在初始化時添加,因爲狀態在頁面循環之間保存。處理控件的內容和視圖狀態應在Load
中完成。
還請檢查http://msdn.microsoft.com/en-us/library/ms178472.aspx。
初始化
畢竟控件都已初始化且已應用所有外觀 設置引發。使用此 事件來讀取或初始化控件 屬性。
。
負載
頁調用頁面上OnLoad事件方法 ,然後遞歸確實的 相同爲每個子控制,其 做同樣對於其每個子的 控制,直到頁面和所有 控件被加載。
使用OnLoad事件方法在控件中設置 屬性並建立 數據庫連接。
當我從Page_Load更改爲Page_Init時,發生同樣的事情。 這行有什麼不對嗎 ib.Click + =購買(g); 因爲它點擊圖像按鈕之前觸發點擊事件! – Kubi 2010-01-18 17:25:36
檢查我的編輯.. – 2010-01-18 17:26:22