Reputation: 85056
I have a ListView that has a Button in the item template. Is there a way for me to identify which Item had it's button clicked from my OnClick event?
I was able to do it with the code below but it seemed crufty. Is there a better way to do this?
((ListViewDataItem)((Button)sender).Parent.Parent)
UPDATE: Was able to implement using the NamingContainer method that one user suggested and then mysteriously removed his answer. Seems like a safer way to do than my original method:
((ListViewDataItem)((Button)sender).NamingContainer)
Upvotes: 1
Views: 153
Reputation: 1
protected void RemoveButton_Click(object sender, EventArgs e)
{
ListViewDataItem item = ((ListViewDataItem)((Button)sender).NamingContainer);
//ListViewDataItem item = (ListViewDataItem)((LinkButton)sender).Parent;
int i = item.DisplayIndex;
DataTable dt = (DataTable)Session["cart"];
dt.Rows[i].Delete();
Listcart.DataSource = dt;
Listcart.DataBind();
Label Lblcart = (Label)Page.Master.FindControl("Lbitem");
Lblcart.Text = Listcart.Controls.Count.ToString();
Session["quantity"] = Lblcart.Text;
Session["cart"] = dt;
GrandTotal();
Session["amount"] = LbGrandTotal.Text;
}
Upvotes: 0
Reputation: 50728
Yes, give the button a command name, then attach to ListView.ItemCommand; clicking the button fires this event, and it has some more specifics about the list item, such as a reference to it via e.Item.
HTH.
Upvotes: 1