简体   繁体   中英

How to get bound object in a repeater's button click event handler?

I have a repeater and bind a list of objects to it, like this:

List<MyClass> myList = //....
MyRepeater.DataSource = myList;
MyRepeater.DataBind();

Inside the repeater I have a link button which is handled by this handler:

protected void Button_ItemCommand(object source, RepeaterCommandEventArgs e) {
    if (e.CommandName == "Edit") {
        // I need to get my listItem.Id here
    }
}

It should be easy but I can't find how to do it.

Thanks.

If you want the actual link button that was clicked, that's already being passed to this method in the object source parameter—just cast it appropriately.

LinkButton lb = source as LinkButton;

If you want some other control that's in your repeater, you can use

Button randomButton = e.Item.FindControl("buttonId") as Button;

EDIT

If you want a property from the object this row is bound to, this will be a pain to do, and it'll be ugly. You'll need to persist the DataSource the repeater is bound to across postbacks, either in Session or ViewState. Once you do that, you can access the appropriate object in the source by matching its index with the index of the reeater's row that was clicked, which you can get by:

e.Item.ItemIndex

Note that the easiest way is to just store this value somewhere in your repeater.

Most of the time it's easy to fetch the bound object from your storage/cache/etc. if you have the ID. Since you said in your question " I need to get my listItem.Id here ", I think you don't mind re-fetching the object itself and are just looking for a way to get only the identifier from the repeater.

Just give the button a command argument as shown:

<asp:LinkButton runat="server" ID="lnkEdit" CommandName="Edit"
  CommandArgument='<%# Eval("ID") %>'>Edit</asp:LinkButton>

Then like you rightly said in your question,

protected void Button_ItemCommand(object source, RepeaterCommandEventArgs e) {
  if (e.CommandName == "Edit") {
    // I need to get my listItem.Id here
    RenderEditDialog(FetchFromStorage(e.CommandArgument.ToString());
  }
}

You cannot do this. The original databound object is not persisted by ASP.Net across postbacks. You have to store the data you want to keep in a control inside the repeater. You can then access the control via the EventArgs, eg

e.Item.FindControl("myControl");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM