代码之家  ›  专栏  ›  技术社区  ›  Andy Evans

ASP.NET::在页面加载期间,如何获取提交回发的控件的ID?

  •  4
  • Andy Evans  · 技术社区  · 14 年前

    在页面加载期间,我想捕获执行回发的控件。

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
    
        }
    
        // Capture the control ID here.
    }
    

    像往常一样,任何想法都会受到极大的赞赏!

    4 回复  |  直到 14 年前
        1
  •  6
  •   Andy Evans    7 年前

    对于任何可能对此感兴趣的人(至少对我有用)。 Cen 提供了答案。

    在页面“加载事件”中添加:

    Control c= GetPostBackControl(this.Page); 
    
    if(c != null) 
    { 
        if (c.Id == "btnSearch") 
        { 
            SetFocus(txtSearch); 
        } 
    }
    

    然后在您的基本页代码中添加:

    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)
            {
                Control c = page.FindControl(ctl);
                if (c is System.Web.UI.WebControls.Button)
                {
                    control = c;
                    break;
                }
            }
    
        }
        return control;
    }
    

    你可以看到原来的帖子 here

    希望这有帮助。

        2
  •  2
  •   womp    14 年前

    你通常可以看看 Request.Params["__EVENTTARGET"] . 此变量将作为回发的结果填充,并将保留导致回发的控件的唯一ID。

    不幸的是,这对按钮或ImageButton控件不起作用。对于在这些情况下获得它的一个非常健壮的方法,您可以 check out this blog post .

        3
  •  1
  •   Cylon Cat    14 年前

    如果有办法的话,我也很想知道!

    但是,您可以为每个可以生成回发的控件设置事件处理程序,并在事件传入时处理它们。

    问题是这些事件是在页面加载后处理的。因此,在这种方法中,您需要为page_prerender添加一个处理程序,并在其中处理控件输入。在页面生命周期中,控件事件在加载之后,但在预呈现之前。

        4
  •  1
  •   M4N    14 年前

    您可以使用请求[“uuEventTarget”]获取调用回发的控件的ID。