Search code examples
asp.netgridviewrepeater

Finding in which row a Button was clicked in a GridView/Repeater


I am binding a Repeater. Each row (is that the right word?) in the Repeater has a Button and a HiddenField. How do I determine the Value of the HiddenField based on which Button was clicked?

Code behind for Button's OnClick event:

protected void btnButton1_Click(object sender, EventArgs e)
{
    Button btnButton1 = (Button)sender;        
    // how do i get this row's HiddenField Value?
}

edit: the CommandArgument suggestion from Pleun works but I am still having issues. I need to find the row(?) in the Repeater that the Button belongs to as there is also a TextBox in each row and I would need its value. So ideally I want to get that row and go FindControl("TextBox1") etc etc. Sorry, should have stated that in my initial question


Solution

  • What I like to do is add a CommandArgument to the button. In this code its an imagebutton but the idea is the same. So also no need for an extra hidden field.

    <asp:ImageButton ID="btnMail" ImageUrl="~/imgnew/prof/sendlink.png" 
    CommandArgument='<%# Eval("id")%>'
    

    And in the _Click event do

     string id = ((ImageButton)sender).CommandArgument;
    

    Update:

    If you need all the data, you need a different event. The data in the repeater is available as Item in

    RepeaterCommandEventArgs 
    

    in the Command event (RepeaterCommandEventArgs)

    for handling the Command event see this example http://www.asp.net/data-access/tutorials/custom-buttons-in-the-datalist-and-repeater-cs or http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeatercommandeventargs.aspx