代码之家  ›  专栏  ›  技术社区  ›  Kubi

以编程方式添加ImageButton

  •  1
  • Kubi  · 技术社区  · 15 年前

    我有如下的代码片段,我想在页面加载期间将imagebuttons添加到我的asp:panel中。但当我运行页面时,事件已经开始了。我要它在点击时被解雇。

    提前谢谢你的帮助

        protected void Page_Load(object sender, EventArgs e)
        {...
    
            foreach (Gift g in bonusGifts)
            {
                ImageButton ib = new ImageButton();
                ib.ImageUrl = g.GiftBanner;
                ib.ID = g.GiftID.ToString();
                ib.Click += Purchase(g);
                BonusGiftPanel.Controls.Add(ib);
    
            }
        }
    
        private ImageClickEventHandler Purchase(Gift g)
        {
            _giftRep.Purchase(g, _userSession.CurrentUser);
            lblGifts.Text = "You have purcased " + g.GiftName + " for " + g.BonusPoints;
    
            return null;
        }
    
    3 回复  |  直到 15 年前
        1
  •  0
  •   user113476    15 年前

    正如其他人所说,您应该在page init事件中添加控件。

    图像单击事件处理程序不符合ImageButton单击事件处理程序签名。看起来应该是这样的:

    private void ImageButton_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
    {
    
    }
    

    请注意,您不能将“礼物”对象直接传递给ImageButton_Click。你必须找到另一种方法。

        2
  •  1
  •   Jan Jongboom    15 年前

    在中添加控件 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):

    必须在页面周期之间维护的所有内容都应在 帕吉尔尼特 不是 页负荷 .

    所有初始化(如添加事件处理程序和添加控件)都应在初始化期间添加,因为状态在页面周期之间保存。处理控件内容和视图状态时,应在 Load .

    也检查 http://msdn.microsoft.com/en-us/library/ms178472.aspx .

    初始化

    在初始化所有控件和任何外观后引发 已应用设置。用这个 要读取或初始化控件的事件 性质。

    .

    负载

    该页调用OnLoad事件方法 在页面上,然后递归执行 每个子控件相同,其中 每个孩子都一样吗 直到页面和所有 控件已加载。

    使用onload事件方法设置 控制和建立属性 数据库连接。

        3
  •  0
  •   Moo    15 年前