Saturday, 27 June 2009

How to Know Which Control Was Clicked?

In aspx.cs:


protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string CtrlID = GetClickedControlID();
ClientScript.RegisterStartupScript(this.GetType()
, "sourceofpostback", "<script type='text/javascript'>window.onload=new function(){alert('Control ID " + CtrlID + " caused postback.');}</script>");

}
private string GetClickedControlID()
{
string CtrlID;
if (String.IsNullOrEmpty(Request.Form["__EVENTTARGET"]))
{
if (String.IsNullOrEmpty(Request.Form[hidSourceID.UniqueID])) return null;
CtrlID = Request.Form[hidSourceID.UniqueID];
}
else
{
CtrlID = Request.Form["__EVENTTARGET"];
}
return CtrlID;
}

In .aspx:
<head runat="server">
<script type = "text/javascript">
function SetSource(SourceID)
{ document.getElementById("<%=hidSourceID.ClientID%>").value = SourceID; } </script>

</head>
<body>
<form id="form1" runat="server">
<asp:HiddenField ID="hidSourceID" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick = "SetSource(this.id)" />
<asp:RadioButton ID="RadioButton1" runat="server" AutoPostBack = "true" />

No comments: