简体   繁体   中英

The LinkButton_Click event is not firing

I have created a dynamic link button. I want to navigate to other pages when the click event is fired . But now, when I click on the link button, the entire page is cleared off and no click event is fired.

 System.Web.UI.WebControls.LinkButton lbView = new System.Web.UI.WebControls.LinkButton();
 lbView.Text = "<br />" + "View";
 lbView.Click += new System.EventHandler(lbView_Click);

 tc.Controls.Add(lbView);
 tr.Cells.Add(tc);

 protected void lbView_Click(object sender, EventArgs e)
 {
     Response.Redirect("contactus.aspx");
 }

Please help.

When you are creating dynamic control you can not directly create click event of that control. In your case you must follow this way. Add javascript to redirect contactus.aspx page.

System.Web.UI.WebControls.LinkButton lbView = new System.Web.UI.WebControls.LinkButton();
lbView.Text = "<br />" + "View";
btn.OnClientClick = "return RedirectTo();";  // You need to add javascript event

tc.Controls.Add(lbView);
tr.Cells.Add(tc);


// javascript
<script>
  function RedirectTo()
  {
     window.location.href = 'contactus.aspx';
     return false;
  }
</script>

Try this. Hope it works for you.

Put your code inside like this and try :-

if(!IsPostBack){
 System.Web.UI.WebControls.LinkButton lbView = new System.Web.UI.WebControls.LinkButton();
 lbView.Text = "<br />" + "View";
 lbView.Click += new System.EventHandler(lbView_Click);

 tc.Controls.Add(lbView);
 tr.Cells.Add(tc);
}

 protected void lbView_Click(object sender, EventArgs e)
 {
     Response.Redirect("contactus.aspx");
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM