user1853803
user1853803

Reputation: 659

Click event on div in asp.net

I have a div in default.aspx with img inside as follow

 <div id="sTab" class="tabs firsttab" runat="server">
     <asp:Image ID="sTabImg"  src="images/home.png" runat="server" />
 Activities
</div>

I want to perform some action on click of the div in ASP.NET (not in javascript).

I tried the following

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
    }

    sTabImg.Attributes["onclick"] = ClientScript.GetPostBackEventReference(this, "ClickDiv");
}

protected void ClickDiv()
{
    Label2.Text = "helo got it";
}

The page is getting refreshed and when i debugged the issue, its not entering the ClickDiv function..What wrong here..

Upvotes: 1

Views: 10834

Answers (2)

Freddie Fabregas
Freddie Fabregas

Reputation: 1203

Why not use ImageButton?

<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>ImageButton Sample</title>
<script language="C#" runat="server">

      void ImageButton_Click(object sender, ImageClickEventArgs e) 
      {
         Label1.Text = "You clicked the ImageButton control at the coordinates: (" + 
                       e.X.ToString() + ", " + e.Y.ToString() + ")";
      }

</script>

</head>
<body>
<form id="form1" runat="server">

  <h3>ImageButton Sample</h3>

  Click anywhere on the image.<br /><br />

  <asp:ImageButton id="imagebutton1" runat="server"
       AlternateText="ImageButton 1"
       ImageAlign="left"
       ImageUrl="images/pict.jpg"
       OnClick="ImageButton_Click"/>

      <br /><br />

      <asp:label id="Label1" runat="server"/>

   </form>

</body>
</html>

And you can see some examples here.

Upvotes: 2

2GDev
2GDev

Reputation: 2466

From Here

public partial class _Default : System.Web.UI.Page, IPostBackEventHandler
{

    protected void Page_Load(object sender, EventArgs e)
    {
       div1.Attributes["onclick"]=ClientScript.GetPostBackEventReference(this,"ClickDiv");
    }

    protected void Div1_Click()
    {
      // Do something
    }

    #region IPostBackEventHandler Members

    public void RaisePostBackEvent(string eventArgument)
    {

      if (!string.IsNullOrEmpty(eventArgument))
      {

              if (eventArgument == "ClickDiv")
              {
                 Div1_Click();
              }
      }
    }

    #endregion
}

You have to implement the IPostBackEventHandler Interface.

Upvotes: 4

Related Questions