4

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

Josh
  • 44,706
  • 7
  • 102
  • 124
MikeL
  • 161
  • 1
  • 4
  • 8
  • 1
    cant you just use that string (which is an ID i assume?) and use that to query your database to get all the elements you need? something like getCustomerById(int id) ? – Thousand Sep 19 '12 at 11:20
  • @JaneDoe - Right. That is what is typically done in these scenarios. Especially since with an ORM the context will not be around anyway for you to hit "save" on. – Josh Sep 19 '12 at 11:29

2 Answers2

6

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") %>'
Scott
  • 21,211
  • 8
  • 65
  • 72
Fonseca
  • 111
  • 4
  • Looks like this is the way I'm going to have to do it, by passing the customer and using that for my delete. – MikeL Sep 19 '12 at 15:26
  • int customerID= Convert.ToInt32(e.CommandArgument.ToString()); this is a serious limitation in the code... you should always use the try.parse – Shakawkaw Dec 17 '15 at 15:58
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.

Josh
  • 44,706
  • 7
  • 102
  • 124