How to find control on GridView RowCommand Event?

Nick Kahn picture Nick Kahn · Jan 31, 2011 · Viewed 20.8k times · Source

i tried something like this but did not work:

GridViewRow row = (GridViewRow)(((Repeater)e.CommandSource).NamingContainer); 
Repeater _rpt1 = row.Cells[8].FindControl("rptReg") as Repeater;

error:

Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.Repeater'.

is there a way i can have the below code in OnRowCommand event using GridView?

actually i am trying to delete the row from the gridview control and when the user click on it and i am grabbing the mulitple ids and passing to SP and update the table and databind the gridview

GridViewRow row = gv.SelectedRow;           
    Repeater _rpt = gv.Rows[e.RowIndex].Cells[8].FindControl("rptReg") as Repeater;
    Repeater _rpt1 = gv.Rows[e.RowIndex].Cells[9].FindControl("rptVisitor") as Repeater;

    foreach (RepeaterItem item in _rpt.Items)
    {
        TextBox _txt = item.FindControl("txtId") as TextBox;
        TextBox _txt1 = item.FindControl("txtName") as TextBox;
        //update db
    }

Answer

Kuntal Maity picture Kuntal Maity · Oct 29, 2012

Please try this:

var viewRow = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
foreach (GridViewRow gvr in gvDetails.Rows)
{
    var btnSelect = (ImageButton)viewRow.FindControl("btnSelect");
    if (gvr == viewRow)
    {
        if (btnSelect.ImageUrl.ToLower() == "~/images/rbnormal.jpg")
        {
            btnSelect.ImageUrl = "~/Images/rbSelected.jpg";
            btnSelect.Enabled = false;
        }
    }
    else
    {
        btnSelect.ImageUrl = "~/Images/rbnormal.jpg";
        btnSelect.Enabled = true;
    }
}