1

I followed this similar post. However, it didn't work and is giving me an error.

How can i create dynamic button click event on dynamic button?

The error is: "Non-invocable member 'System.Web.UI.WebControls.ImageButton.OnClientClick' cannot be used like a method."

The code I am trying is:

ImageButton appIcon2 = new ImageButton();
appIcon2.OnClientClick(){ }
Community
  • 1
  • 1
Vrutin Rathod
  • 900
  • 1
  • 12
  • 16

2 Answers2

1

on client click takes javascript function i.e myImgButton.OnClientClick="return confirm('Are you sure?');";

if you want to do "Click" function just do this

ImageButton appIcon2 = new ImageButton();
appIcon2.Click  += new System.Web.UI.ImageClickEventHandler(appIcon2_Click);

void appIcon2_Click(object sender, ImageClickEventArgs e)

    {

       // Your Code here

    }

if you want to access this image button you can cast sender as image button as follows

void appIcon2_Click(object sender, ImageClickEventArgs e)

    {

       ImageButton imgBtn= sender as ImageButton;
       string id= imgBtn.ID;



    }
Yosra Galal
  • 316
  • 2
  • 10
1

OnClientClick accepts a string value i.e. it is supposed to point to a javascript code block.

you can either do this.

appIcon2.OnClientClick = "alert('s')";

or

appIcon2.OnClientClick = "myMethod()";

where myMethod() is a javascript function defined in the html head or body of the page i.e.

function myMethod(){
   alert('s');
} 

as for the link that you have posted, it simply says how can you directly add an event handler to a button. i.e.

protected void Page_Load(object sender , EventArgs)
{
   ImageButton appIcon2 = new ImageButton();
   appIcon2.Click += new System.Web.UI.ImageClickEventHandler(btn_Click);
}

void btn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
   //your logic
}

note that Click is an event. it is associated with server side controls

Manish Mishra
  • 12,163
  • 5
  • 35
  • 59