动态获取单击的服务器端控件的id值

private string getPostBackControlName()
    {
        Control control=null;
        string ctrlname = Page.Request.Params["__EVENTTARGET"];
        if (ctrlname != null && ctrlname != String.Empty)
        {
            control = Page.FindControl(ctrlname);
        }
        else
        {
            Control c;
            foreach (string ctl in Page.Request.Form)
            {
                if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                {
                    c = Page.FindControl(ctl.Substring(0, ctl.Length - 2));
                }
                else
                {
                    c = Page.FindControl(ctl);
                }
                if (c is System.Web.UI.WebControls.Button ||
                         c is System.Web.UI.WebControls.ImageButton)
                {
                    control = c;
                    break;
                }
            }
        }
        if (control != null)
            return control.ID;
        else
            return string.Empty;
    }

ps:

There are two types of controls which make post back in ASP.NET. One button type control like image button, button (whose type is “submit”), and another type use javascript function “_doPostBack” for the post back.

If post back control is button type then it will be added in the Request.Form collection means if there are two button in a page named button1 and button2 and if button1 make post back then only button1 will be in Request.Form Collection not button2 (but Request.Form collection can contains other server controls also like if page contains few textbox, dropdown list etc.) and if post back made by the button2 then only button2 will be available in Request.Form collection not button1(with other server control as I discuss earlier).

So if you want to catch which button type control made a post back in page load event, you have to just iterate the Request.Form collection.

I’ll show you demo latter in this article.

Another category of server control who make post back use the client side javascript function _doPostBack like if we made autopostback true for dropdown list, radio button etc.

If you look view source you will found _doPostBack javascript function.

function __doPostBack(eventTarget, eventArgument)

{

if  (!theForm.onsubmit || (theForm.onsubmit() ! =   false ))

{

theForm.__EVENTTARGET.value  =  eventTarget;

theForm.__EVENTARGUMENT.value  =  eventArgument; theForm.submit();

}

}

As you can see this function take two arguments “eventTarget” and “eventArgument”. “eventTarget” used for the control ID who is responsible for the postback and “eventArgument” used for the additional information about the control.

If you look at the view source you will also found these two hidden fields.

<input type= "hidden"  name= "__EVENTTARGET"  id= "__EVENTTARGET"  value= ""  />

<input type= "hidden"  name= "__EVENTARGUMENT"  id= "__EVENTARGUMENT"  value= ""  />

Lets add one dropdown server control in page and make autopostback true also add some dummy data. If you look at the view source you will found

<select name="DropDownList1" onchange="javascript:setTimeout('__doPostBack(\'DropDownList1\',\'\')', 0)" id="DropDownList1">

<option value="1">abc</option>

<option value="2">xyz</option>

</select>

ASP.NET engine automatically add onchange event and call the _doPostBack function and pass the appropriate parameter.

_doPostBack function first set the value of those hidden field and then submit the form. So if you want to know whether this dropdown list make post back or not you have to just check the value of “__EVENTTARGET” hidden field from the form parameter collection. I’ll show you code as well.

In my example I am adding two buttons, one image button, one dropdown list, one checkbox and two image buttons. I’ll try to print the control name which makes the post back. All I’ll try to find in page load event. So be ready for the ride.

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (IsPostBack)

Response.Write(getPostBackControlName());

}

private string getPostBackControlName()

{

Control control = null;

//first we will check the "__EVENTTARGET" because if post back made by       the controls

//which used "_doPostBack" function also available in Request.Form collection.

string ctrlname = Page.Request.Params["__EVENTTARGET"];

if (ctrlname != null && ctrlname != String.Empty)

{

control = Page.FindControl(ctrlname);

}

// if __EVENTTARGET is null, the control is a button type and we need to

// iterate over the form collection to find it

else

{

string ctrlStr = String.Empty;

Control c = null;

foreach (string ctl in Page.Request.Form)

{

//handle ImageButton they having an additional "quasi-property" in their Id which identifies

//mouse x and y coordinates

if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))

{

ctrlStr = ctl.Substring(0, ctl.Length - 2);

c = Page.FindControl(ctrlStr);

}

else

{

c = Page.FindControl(ctl);

}

if (c is System.Web.UI.WebControls.Button ||

c is System.Web.UI.WebControls.ImageButton)

{

control = c;

break;

}

}

}

return control.ID;

}

}

如何在page_load方法判断是服务器端控件引发的page_load方法的更多相关文章

  1. 如何在js中获取到服务器端控件并给其赋值

    如下所示:lbID为服务器端控件ID document.getElementById('<%=lbID.ClientID%>').value = "赋值";

  2. 不使用ASP.NET服务器端控件(包括form表单不加runat="server")来触发.cs里的事件(方法),(适用于有代码洁癖者)。

    很多时候,我们使用服务器端控件写出的代码,会给我们生成一些很多我们看不懂的代码(初学者),但是有时候我们并不需要这些代码(业务需求不同),对于生成的一些代码感到多余.所以我就开始想,有没有一种可能:不 ...

  3. jquery dialog open后,服务器端控件失效的快速解决方法

    jquery dialog为我们提供了非常漂亮实用的对话框,比单调的alert.confirm.prompt好用很多. 在使用jquery与.net共同开发时,直接调用jquery dialog的op ...

  4. 17Web服务器端控件

    Web服务器端控件 Web服务器端控件 ASP.Net提供了两类服务器端控件:Html服务器端控件和Web服务器端控件.由于Web服务器端控件功能更强大,和Windows应用程序的控件使用方法类似,容 ...

  5. .net学习之母版页执行顺序、jsonp跨域请求原理、IsPostBack原理、服务器端控件按钮Button点击时的过程、缓存、IHttpModule 过滤器

    1.WebForm使用母版页后执行的顺序是先执行子页面中的Page_Load,再执行母版页中的Page_Load,请求是先生成母版页的控件树,然后将子页面生成的控件树填充到母版页中,最后输出 2.We ...

  6. ASP.NET服务器端控件(class0617)

    ASP.Net服务端基本控件介绍 ASP.Net服务端控件是ASP.Net对HTML的封装,在C#代码中就可以用txt1.Text=‘abc’这种方式来修改input的值,ASP.Net会将服务端控件 ...

  7. javascript获取asp.net服务器端控件的值

    代码如下: <%@ Page Language="C#" CodeFile="A.aspx.cs" Inherits="OrderManage_ ...

  8. Asp.Net 之 服务器端控件与客户端控件的区别

    服务器控件,即Asp.Net的控件,控制这些控件必须经过服务器处理,然后响应用户,代码在服务器端解释执行,生成根据用户的浏览器而定的html元素. 客户端控件,即普通Html控件,使用script控制 ...

  9. Chart控件的多种使用方法

    花了近一周时间专门研究.net 3.5平台提供的Chart控件的使用方法,感觉该控件的功能很强大,做出的图表效果也很美观,使用方法也并不复杂.如今先讲下Chart控件的部署及一些基本使用方法. 一.安 ...

随机推荐

  1. 在Eclipse中在线安装Emmet和图文使用教程

    ZenCoding 升级为 Emmet 之后,基于 Eclipse 的插件安装地址也发生了变化, 下面是在基于 Eclipse 的 IDE 中安装和使用 Emmet 的图文示例. 一.打开 Eclip ...

  2. java之redis篇(spring-data-redis整合一)

    redis的知识:官网 1.利用spring-data-redis整合 项目使用的pom.xml: <project xmlns="http://maven.apache.org/PO ...

  3. Html Mailto标签详细使用方法

    Html中mailto标签是一个非常实用的贴近用户体验的标签,大多情况下人们都在这样使用 <a href="mailto:example@phplamp.com">ex ...

  4. Qt Load and Save PCL/PLY 加载和保存点云

    Qt可以跟VTK和PCL等其他库联合使用,十分强大,下面的代码展示了如何使用Qt联合PCL库来加载和保存PCL/PLY格式的点云: 通过按钮加载点云: void QMainWindow::on_pb_ ...

  5. 打造移动终端的 WebApp(一):搭建一个舞台

    最近随着 Apple iOS 和 Android 平台的盛行,一个新的名词 WebApp 也逐渐火了起来,这里我也趁着热潮做一个关于 WebApp 系列的学习笔记,分享平时的一些研究以及项目中的经验, ...

  6. CVTRES : fatal error CVT1100 , fatal error LNK1123:

    CVTRES : fatal error CVT1100: duplicate resource. type:DIALOG, name:901, language:0x0804LINK : fatal ...

  7. cms修改后台目录

    if (!_dirName.Equals("manage")) { if (PageType.IndexOf(_dirName) != -1) { PageType = PageT ...

  8. Linux学习笔记---用户管理---帐号管理

    root管理 (1)新增用户:useradd -u 指定UID -g 指定GID -G 作为组员添加到某个组 -M 不创建主用户目录 -m 创建主用户目录 -c 用户信息说明列 -d 指定某个目录为主 ...

  9. codeforces575A Fibonotci

    题目大意:f[k]=f[k-1]*s[(n-1)%n]+f[(k-2)]*s[(k-2)%n];会修改某一位置的s值,但循环不变,求f[k]; 矩阵快速幂裸题,由于有修改,所以需要线段树优化 #inc ...

  10. 获取AndroidManifest.xml文件中的meta-data

    以获取高德地图的key值为例 <meta-data android:name="api_key" android:value="l8o0DhNxmvPDpCxTab ...