Abe Miessler
Abe Miessler

Reputation: 85056

How to capture an event in a ListView?

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

Answers (2)

Pankaj Kumar
Pankaj Kumar

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

Brian Mains
Brian Mains

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

Related Questions