views:

382

answers:

2

I have an ASP.NET page with code-behind in VB.NET. On the ASPX page I have a Repeater with an asp:ImageButton inside the repeater and I want to catch the clicks on the button. As far as I read I have to use FindControl and then handle the copy of the original control:

Codebehind:    
Dim imagebutton1 As ImageButton = repeater.FindControl("btnImage1")
AddHandler imagebutton1.Command, AddressOf ReportTransfer
...
...
Protected Sub ReportTransfer(ByVal sender As ImageButton, ByVal args As CommandEventArgs)
...
End Sub

ASPX page:

                <td>
                    <asp:ImageButton runat="server" ID="btnImage1" ImageUrl="~/images/icons/icon_small.png"
                                     CommandArgument="3" />
                </td>
            </tr>
        </ItemTemplate>

It throws "Object reference not set to an instance of an object" on the AddHandler line and I have no idea why it is doing it (I'm a bit new with VB.NET)

Thank you in advance

+1  A: 

You're getting "Object reference not set to an instance of an object" because imagebutton1 is null. Make sure you're actually finding a control before adding a handler.

AMissico is right, you want to actually subscribe to the Repeater's ItemCommand event, and use the CommandArgument to identify what row the user clicked on.

Aaron Daniels
You're right...I updated it and credited you. I had a brain lapse, and didn't even consider the context of the question.
Aaron Daniels
Happens. :O) I got really good at repeaters after my last web project. I had to nest and group multiple repeaters.
AMissico
It's funny because I've used buttons in a repeater a million times. However, I was so focused on the AddHandler I didn't even think about what he was actually doing.
Aaron Daniels
+1  A: 

You should be handling ItemCommand event of the Repeater. In this event CommandSource is the image button. Either the CommandArgument or CommandName needs to indicate what command you actually want to perform. Setting the CommandArgument to 3, means each image button will have the same value.

The repeater.FindControl("btnImage1") is not going to work because each button's id is going to change.

Adding the handler is not correct.

Repeater.ItemCommand Event; Occurs when any button is clicked in the Repeater control; http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemcommand.aspx

AMissico