我有一個頁面,我動態添加ImageButtons。我首先設置了按鈕的OnClientClick
,以簡單地顯示放大圖像的彈出窗口,並返回false,無回傳。動態添加ImageButton命令事件不會觸發,直到第二次點擊
我在頁面上有一個按鈕來設置「主圖像」,所以當點擊這個按鈕時,我設置一個名爲_IsSettingPrimaryPhotoMode = true
的屬性,調用該函數重新創建ImageButtons,並且在創建ImageButton時,如果此屬性爲true添加一個OnClientClick
,我連接CommandEventHandler
,所以我可以通過閱讀CommandArgument
來分辨哪個按鈕被點擊了。
問題是事件處理程序不會在第一次點擊圖像時觸發,而只會在第二次點擊之後觸發。我還將代碼從Page_Load
移至OnInit
,並在每次回傳中加載ImageButton。我們將_IsSettingPrimaryPhotoMode
保存爲Session
。
private bool _IsSettingPrimaryPhotoMode {
get {
bool result = false;
if(Session[ConstantsWeb.Session.IS_DELETE_IMAGE_MODE] != null) {
result = Convert.ToBoolean(Session[ConstantsWeb.Session.IS_SETTING_PRIMARY_IMAGE_MODE]);
}
return result;
}
set {
Session[ConstantsWeb.Session.IS_SETTING_PRIMARY_IMAGE_MODE] = value;
}
}
頁的OnInit
protected override void OnInit(EventArgs e) {
base.OnInit(e);
if(!IsPostBack) {
_IsSettingPrimaryPhotoMode = false;
}
_LoadGalleryImages();
}
}
的_LoadGalleryImages方法
private void _LoadGalleryImages() {
PhotoGalleryImageCollection images = PhotoGalleryImages.GetPhotoGalleryImages();
foreach(PhotoGalleryImage image in images) {
ImageButton displayImage = new ImageButton();
Panel panel = new Panel();
panelPhotoContainer.Controls.Add(panel);
displayImage.ImageUrl = "some URL";
if(!_IsSettingPrimaryPhotoMode) {
displayImage.OnClientClick = "showPopup(); return false;";
}
else {
displayImage.Command += new CommandEventHandler(displayImage_Command);
displayImage.CommandName = "ImageButton" + image.PhotoGalleryImageId.ToString();
displayImage.CommandArgument = image.PhotoGalleryImageId.ToString();
}
panel.Controls.Add(displayImage);
}
}
btnSetPrimaryPhoto_Click
protected void btnSetPrimaryPhoto_Click(object sender, EventArgs e) {
// if I don't call this, duplicate controls will be added since they were added
// from OnInit calling _LoadGalleryImages();
panelPhotoContainer.Controls.Clear();
_IsSettingPrimaryPhotoMode = true;
// reload since _IsSettingPrimaryPhotoMode has now changed
_LoadGalleryImages();
}
我在做什麼錯?
嘗試添加此代碼,看看它是否會解決您的問題displayImage.Command - = new CommandEventHandler(displayImage_Command); – MethodMan 2012-02-23 17:43:47
爲什麼在按鈕點擊和另一個事件中調用_LoadGalleryImages()? – 2012-02-23 18:42:12