get submit button id

Inside asp.net form I have few dynamically generated buttons, all of this buttons submit a form, is there a way to get which button was submit the form in page load event?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The sender argument to the handler contains a reference to the control which raised the event.

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

Edit: Wait, in the Load event? That’s a little tricker. One thing I can think of is this: The Request’s Form collection will contain a key/value for the submitting button, but not for the others. So 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..

Method 2

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

Method 3

This won’t work if your code is inside a user control:

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

Instead you can try this:

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

Method 4

You could try:

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

}

Method 5

please try this code in page load event

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

if eventtriggeredCategory is returning any value its fired the event of ddlCategory

this is works fine for me

Thanks
Jidhu

Method 6

Request.Form["__EVENTTARGET"] will give you the button that fired the postback

Method 7

Use CommandArgument property to determine which button submits the form.

Edit : I just realized, you said you need this at PageLoad, this works only for Click server side event, not for PageLoad.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x