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

And*_*ans 4 asp.net postback

在Page_Load期间,我想捕获执行回发的控件.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {

    }

    // Capture the control ID here.
}
Run Code Online (Sandbox Code Playgroud)

像往常一样,任何想法将不胜感激!

And*_*ans 6

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

在您的Page_Load事件中添加:

Control c= GetPostBackControl(this.Page); 

if(c != null) 
{ 
    if (c.Id == "btnSearch") 
    { 
        SetFocus(txtSearch); 
    } 
}
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到原帖

希望这可以帮助.