如何解决InvalidCastException未被用户代码处理?

时间:2013-12-09 10:48:09

标签: c# asp.net

GridViewRow row=((GridViewRow )((ImageButton )e.CommandSource ).NamingContainer );
ImageButton imgdelete = (ImageButton)row.FindControl("imgdelete");

string pid = e.CommandArgument.ToString();
if (e.CommandName == "Edit"){
    Response.Redirect("PatientRegistration.aspx?pdid=" + pid);
}
if (e.CommandName == "Delete"){
    BL_Property.PatientID = pid;
    BL_Patient.DeletePatient(BL_Property);
    ShowAllPatient();
}

我使用了两个图像按钮进行编辑和删除当我点击下一页时我得到了第一页我收到了错误

InvalidCastException was unhandled by User code
Error Message :- Unable to cast object of type 'System.Web.UI.WebControls.GridView' to type 'System.Web.UI.WebControls.ImageButton'

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

GridViewRow row= (GridViewRow)(((ImageButton )e.CommandSource).NamingContainer);
mageButton imgdelete = (ImageButton)row.FindControl("imgdelete");

答案 1 :(得分:0)

您正试图在代码行中将System.Web.UI.WebControls.GridView转换为System.Web.UI.WebControls.ImageButton,并将括号(放错地方,

GridViewRow row=((GridViewRow )((ImageButton )e.CommandSource ).NamingContainer );

试试这个,

GridViewRow row = (GridViewRow)  (((ImageButton)e.CommandSource).NamingContainer);