获取提交按钮ID

时间:2009-10-08 10:25:16

标签: c# .net asp.net

在asp.net表单中我有几个动态生成的按钮,所有这些按钮都提交了一个表单,是否有办法在页面加载事件中提交哪个按钮提交表单?

7 个答案:

答案 0 :(得分:8)

处理程序的sender参数包含对引发事件的控件的引用。

private void MyClickEventHandler(object sender, EventArgs e)
{
    Button theButton = (Button)sender;
    ...
}

编辑:等待,在加载事件中?那是一个小问题。我能想到的一件事是:Request的Form集合将包含提交按钮的键/值,但不包含其他键。所以你可以这样做:

protected void Page_Load(object sender, EventArgs e)
{
    Button theButton = null;
    if (Request.Form.AllKeys.Contains("button1"))
        theButton = button1;
    else if (Request.Form.AllKeys.Contains("button2"))
        theButton = button2;
    ...
}

不是很优雅,但你明白了......

答案 1 :(得分:1)

protected void Page_Load(object sender, EventArgs e) {            
    string id = "";
    foreach (string key in Request.Params.AllKeys) {
        if (!String.IsNullOrEmpty(Request.Params[key]) && Request.Params[key].Equals("Click"))
            id = key;
    }
    if (!String.IsNullOrEmpty(id)) {
        Control myControl = FindControl(id);
        // Some code with myControl
    }
}

答案 2 :(得分:0)

如果您的代码位于用户控件中,则无效:

Request.Form.AllKeys.Contains("btnSave") ...

相反,你可以试试这个:

if (Request.Form.AllKeys.Where(p => p.Contains("btnSave")).Count() > 0)
{
    // btnSave was clicked, your logic here
}

答案 3 :(得分:0)

你可以尝试:

if (this.Page.Request.Form[this.btnSave.ClientID.Replace("_", "$")] != null) {

}

答案 4 :(得分:0)

请在页面加载事件中尝试此代码

string eventtriggeredCategory = Request.Form["ctl00$ContentPlaceHolder1$ddlCategory"];

如果eventtriggeredCategory返回任何值,则触发ddlCategory事件

这对我来说很好用

由于 Jidhu

答案 5 :(得分:0)

Request.Form["__EVENTTARGET"]将为您提供触发回发的按钮

答案 6 :(得分:-2)

使用CommandArgument属性确定提交表单的按钮。

编辑:我刚刚意识到,你说你需要在PageLoad中使用它,这只适用于Click服务器端事件,而不适用于PageLoad。