Get submit button id

Inside an asp.net form I have some dynamically generated buttons, all of these buttons represent the form, is there a way to get which button submitted the form in the page load event?

+2


source to share


7 replies


The argument sender

to the handler contains a reference to the control that raised the event.

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

      

Edit: Wait, at the loading stage? This is a bit of a trick. One thing I can think of is this: the collection of the request form will hold the key / value for the submit button, but not the rest. Therefore, you can do something like:



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;
    ...
}

      

Not very elegant, but you get the idea ...

+8


source


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
    }
}

      



+1


source


This won't work if your code is inside a custom control:

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

      

You can try this instead:

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

      

0


source


You may try:

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

}

      

0


source


try this code on page load event

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

      

if eventtriggeredCategory returns any value, it fired ddlCategory event

this works great for me

Thanks Jidhu

0


source


Request.Form["__EVENTTARGET"]

will give you the button where the postback was made

0


source


Use the CommandArgument property to determine which button represents the form.

Edit: I just got it, you said you need this in PageLoad, this only works for the Click server side event, not for PageLoad.

-2


source







All Articles