0

I have 2 buttons and in the page load, and I want to check which button is pressed.

So I used:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            if (string.IsNullOrEmpty(Request.Form["__EVENTTARGET"].ToString()))
            {
                [COMES HERE]
            }
            else
            {
                string eTarget = Request.Form["__EVENTTARGET"].ToString();
            }           
        }
        else
        {
            LoadAllData();
        }
    }

Here, after I press the button, it comes as null. How can I know which button is pressed?

Drew Kennedy
  • 4,118
  • 4
  • 24
  • 34
user1989
  • 217
  • 2
  • 13
  • 1
    Check out [this link](http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx), looks like buttons do not init EVENTTARGET field – Andrei Jan 29 '15 at 19:02
  • 1
    see: http://stackoverflow.com/questions/3175513/on-postback-how-can-i-check-which-control-cause-postback-in-page-init-event – Habib Jan 29 '15 at 19:03

2 Answers2

0

You need to cause the postback manually, and send the button's id back to the server using the ASP.NET's built in function __doPostBack("target","arguments")

first of all, on your aspx page create a js function that will be called by the buttons on the client-side:

function ManualPostback(postbackTarget) {
    __doPostBack(postbackTarget.id, "");
}

now, on your buttons you need to add 2 new attributes:

  • OnClientClick - this will call the js function when client clicks the button
  • ClientIDMode="static" - this tells ASP.NET to let the buttons keep the id's that you assign them, and not generate new ones for clientside as it does by default

your buttons should look like that:

<asp:Button ClientIDMode="Static" ID="Button1" runat="server" Text="Button" OnClientClick="ManualPostback(this);"/>
<asp:Button ClientIDMode="Static" ID="Button2" runat="server" Text="Button" OnClientClick="ManualPostback(this);" />
Banana
  • 7,424
  • 3
  • 22
  • 43
0

For your code to work it looks like you have to have UseSubmitBehavior="false"

for example:

<asp:Button runat="server" ID="btn1" Text="Button 1" OnClick="btn1_Click" UseSubmitBehavior="false"  />
John Boker
  • 82,559
  • 17
  • 97
  • 130