动态获取单击的服务器端控件的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. #define is unsafe——I

    I. #define is unsafe Have you used #define in C/C++ code like the code below? #include <stdio.h&g ...

  2. [zt]OpenCV如何获取视频当前的一帧图像

    (OpenCV读取视频.OpenCV提取视频每一帧.每一帧图片合成新的AVI视频)CvCapture 是视频获取结构 被用来作为视频获取函数的一个参数 比如 CvCapture* cap; IplIm ...

  3. 获取Android studio的SHA1值

    D:\Android\BaiduMapsApiASDemo>c: C:\>cd .android 系统找不到指定的路径. C:\>cd Users C:\Users>cd Ad ...

  4. TestStand与LabVIEW UI 交互

    交互起因 客户觉得TestStand界面复杂,希望一个简单的界面即可进行序列执行,采用LabVIEW调用TestStand引擎可实现快速设计,将TestStand拆解到LabVIEW.然而,这样做需要 ...

  5. C++STL -- vector 使用

    vector是一种顺序容器. vector常用API: 现在一个个分析: 1. assign 这是一种赋值方法,但是会覆盖原来容器内的值. void assign( size_type num, co ...

  6. Android课程---用进度条改变图片透明度

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...

  7. php课程---练习连接数据库及增删改

    方式一:用php中的内置函数来做 (适用于5.1之前的版本) //1.生成连接 $conn = mysql_connect("localhost","root" ...

  8. IOS第16天(5,Quartz2D雪花)

    *** #import "HMView.h" @interface HMView() { int count; } @property (nonatomic, assign) CG ...

  9. 内省操作javabean的属性

    import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector ...

  10. phpqrcode不能输出二维码

    phpqrcode不能输出二维码  注意 权限.....  注意 扩展 header('Content-Type: image/png'); include_once 'phpqrcode/qrlib ...