Pass object as CommandArguement in a Repeater Link Button

15,455

Solution 1

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") %>'

Solution 2

The issue you are running into here is that you repeater has to get translated into HTML. Therefore you are constrained to the limits of what is allowed by the specification in an element attribute.

On the server side CommandArgument will always be a string, so you cannot do what you want as you have it coded.

Now... there are several hacks you could implement to get around this, like the aforementioned CSV, or you could use binary serialization and Base64 encode the result. However, these are all terrible solutions!

What you need is to re-think how you are doing this. I promise there is an easier way.

Share:
15,455
MikeL
Author by

MikeL

Updated on July 01, 2022

Comments

  • MikeL
    MikeL almost 2 years

    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

  • MikeL
    MikeL over 11 years
    Looks like this is the way I'm going to have to do it, by passing the customer and using that for my delete.
  • Shakawkaw
    Shakawkaw over 8 years
    int customerID= Convert.ToInt32(e.CommandArgument.ToString()); this is a serious limitation in the code... you should always use the try.parse