如何在GridView RowCommand事件上找到控件?

时间:2011-01-31 22:28:49

标签: asp.net gridview aspxgridview

我尝试过这样的事情,但没有奏效:

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

错误:

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

有没有办法在OnRowCommand事件中使用GridView获得以下代码?

实际上我正在尝试从gridview控件中删除该行,当用户点击它时,我抓住多个id并传递给SP并更新表格并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
    }

2 个答案:

答案 0 :(得分:3)

请试试这个:

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;
    }
}

答案 1 :(得分:0)

您的错误告诉我名为“rptReg”的控件是一个按钮。

GridView有一个名为DataKeys的属性,可以容纳多个ID 所以你会把“PersonId”拉出来:

     string personId = GridView1.DataKeys[e.RowIndex]["PersonId"].ToString();