现在的位置: 首页 > 综合 > 正文

How to detect which control caused postback

2012年07月01日 ⁄ 综合 ⁄ 共 2335字 ⁄ 字号 评论关闭

 

 public static Control GetPostBackControl(Page page)
    
{
        Control control 
= null;
        
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
        
if (ctrlname != null && ctrlname != string.Empty)
        
{
            control 
= page.FindControl(ctrlname);
        }

        
else
        
{
            
foreach (string ctl in page.Request.Form)
            
{
               
if ((ctl.LastIndexOf(".x"> 0|| (ctl.LastIndexOf(".y"> 0))
                
{
                    control 
= page.FindControl(ctl.Substring(0, ctl.Length - 2));
                    
break;
                }

                control 
= page.FindControl(ctl);  
                
if ((control is System.Web.UI.WebControls.Button))
                
{
                    
break;
                }

             }

          }

        
return control;
        }

 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class WebUserControl : System.Web.UI.UserControl
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (IfInThisControl(this))
        
{
            Label1.Text 
= DateTime.Now.ToString();
        }

    }


    
public static bool IfInThisControl(Control theControl)
    
{
        
string ctrlname = theControl.Page.Request.Params.Get("__EVENTTARGET");

        
if (ctrlname != null && ctrlname != string.Empty)
        
{
            
if (ctrlname.StartsWith(theControl.ClientID) || ctrlname.StartsWith(theControl.UniqueID))
                
return true;
            
else
                
return false;
        }

        
else
        
{
            
foreach (string ctl in theControl.Page.Request.Form)
            
{
                
if (ctl != null)
                
{
                    Control c 
= theControl.Page.FindControl(ctl);
                    
if (c is Button && (c.ClientID.StartsWith(theControl.ClientID) || c.ClientID.StartsWith(theControl.UniqueID)))
                    
{
                        
return true;
                    }

                }

            }

        }

        
return false;
    }


    
protected void Timer1_Tick(object sender, EventArgs e)
    
{
        Label2.Text 
= DateTime.Now.ToString();
    }

}

 

抱歉!评论已关闭.