2

I am new to custom controls in asp.net. I am facing difficulty while attaching the click event handler for the image button. I written the following code for server control.

        ImageButton _imgbtn;
        TextBox txtOutput;
        Label _lblname;
        public ImageButton searchBtn
        {
            get { return _imgbtn; }
            set { _imgbtn = value; }
        }

        public Label lblName
        {
            get { return _lblname; }
            set { _lblname = value; }
        }
        protected override void OnInit(EventArgs e)
        {
             txtOutput = new TextBox();
            txtOutput.Width = 180;
            txtOutput.ID = "ResultOutput";
            txtOutput.Enabled = false;
            Controls.Add(txtOutput);

            searchBtn = new ImageButton();
            Controls.Add(searchBtn);
            lblName = new Label();
            lblName.Text = "";
            Controls.Add(lblName);

        }
        protected override void RenderContents(HtmlTextWriter output)
        {
            //base.Render(output);
            txtOutput.RenderControl(output);
            searchBtn.RenderControl(output);
            lblName.RenderControl(output);
        }

I added this custom control to the .aspx page with register tag as follows.

<%@ Register TagPrefix="mycontrol" Namespace="MyControl" Assembly="MyControl" %> 

In aspx.cs file I give the property values as below,

        CustomControl mycustctrol;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                mycustctrol = myCust as CustomControl;
                mycustctrol.searchBtn.ImageUrl = "~/Images/searchicon.png";
                mycustctrol.searchBtn.OnClientClick = "GenerateClickEvent"

            }
        }


public void GenerateClickEvent(object sender, EventArgs args)
    {
        mycustctrol.lblName.Text = "clicked";
    }

After running this application I am getting the following error.

'GenerateClickEvent' is undefined

Where I done the mistake. I tried with declaring an event like public event EventHandler GenerateClickEvent;, but I am unable to go further. Can you please show me the way how to achieve this.

I also tried with the javascript function in the .aspx page as

function GenerateClickEvent() {

        alert('clicked');
    }

alert('clicked'); is not firing.

4

1 回答 1

2

you probably want something like this what you are doing is for client click

 mycustctrol.searchBtn.OnClientClick = "GenerateClickEvent()"

and something like this for the event click

 mycustctrol.searchBtn.Click += new ImageClickEventHandler(GenerateClickEvent_Click);

 protected void GenerateClickEvent_Click(object sender, ImageClickEventArgs e) 
  {
        mycustctrol.lblName.Text = "clicked";
  }
于 2012-12-04T06:04:42.457 回答