Pass object as CommandArguement in a Repeater Link Button

MikeL picture MikeL · Sep 19, 2012 · Viewed 15k times · Source

I have a Repeater with a list of Customers. Against each customer there is a delete link button. As part of the linkbutton I want to pass the Customer object to the Command Arguement as follows (where Container.DataItem is the customer object):

<asp:LinkButton  ID="lnkDelete" 
   OnClientClick="return confirmDelete();"  
   OnClick="Customer_OnDelete"  
   CommandArgument="<%# Container.DataItem  %>"  
   CommandName="Delete" 
   runat="server"></asp:LinkButton>

When I do this:

    var button = (((LinkButton) sender));

    var customer=  button.CommandArgument;

button.CommandArguement is a string. I need all the object properties as we are using Nhibernate so everything needs to be set, the ID of the deleted record is not enough. I have seen examples online regarding passing a comma seperated list of values into the command arguement but want to avoid doing that. Is this possible?

Any ideas? Thanks

Answer

Fonseca picture Fonseca · Sep 19, 2012

In my opinion the best way for this case is:

  • Get the ID from CommandArgument
  • Get the Customer by ID
  • Delete the Customer Entity

Use the Repeater event OnItemCommand. This event contains RepeaterCommandEventArgs. You cant get the CommandArgument this way:

protected void myRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
   int customerID= Convert.ToInt32(e.CommandArgument.ToString());
}

At your asp:LinkButton tag use:

CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID") %>'