1

此方法位于不在 webForm 中的 cs 类中,我在其中创建了一些 div 和类,但我想创建方法( objImage.Attributes.Add("OnClientClick", "amethod(objRssItem)"); )amethod 在 webform 中的另一个 .cs 中。单击图像按钮时,我无法使用此方法。我该怎么做?谢谢

public HtmlGenericControl CreateDIV_OyVerme_Sub_Yildiz(string id, int subId, Rss.Items objRssItem)
    {
        HtmlGenericControl objDiv = new HtmlGenericControl("div");
        objDiv.ID = strControlName_DivYildiz + id + "_" + subId;

        objDiv.Attributes.Add("class", strClassName_DivYildiz);
        //objDiv.Attributes.Add("runat", "server");

        ImageButton objImage = new ImageButton();
        objImage.Attributes.Add("runat", "server");

        //objImage.Src = strImgSrc_yildiz;
        //objImage.Click += new ImageClickEventHandler(WebForm4.ImageButtons_Click);


        objImage.ID = strControlName_ImageYildiz + id +"_" + subId;;
        objImage.ImageUrl = strImgSrc_yildiz;
        objImage.OnClientClick = strOnClientClickFunc_yildiz;
        objImage.Style.Add(HtmlTextWriterStyle.Height, "19px");
        objImage.Style.Add(HtmlTextWriterStyle.Width, "20px");
        objImage.Style.Add(HtmlTextWriterStyle.BorderWidth, "0px");
        objImage.Style.Add(HtmlTextWriterStyle.Position, "relative");
        objImage.Style.Add(HtmlTextWriterStyle.Top, "13px");
        objImage.Style.Add(HtmlTextWriterStyle.Left, "6px");
        objImage.Style.Add("float", "left");
        objImage.ToolTip = subId + "/" + 5;
        // calling the method 
        objImage.Attributes.Add("OnClientClick", "amethod(objRssItem)");
        objDiv.Controls.Add(objImage);

        return objDiv;
    }
4

1 回答 1

0

OnClientClick is for JavaScript. I believe you are looking to call a cs method. If you want to call a cs method then it should be clear. You use the click function of the code behind for the button. If the problem is this is a dynamic object (as you show.) Then try this

  objImage.Click += myfunctiontocall;

Remember this will happen in postback and if you don't re-create the object (with the same click handler) the call of your function will not work. You need to "re-wire" it every time.


To give a parameter to an event you can wrap a closure like so.

  var duck = objRssItem;

  objImage.Click += (s,e) => { WebForm4.amethod (duck); };

Remember closures are a tricky business -- you are calling amethod with what has become global. Strange things can happen.

于 2012-03-19T17:26:42.583 回答