一个删除记录的操作,代码如下:
 Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
        
        If e.Row.RowState = DataControlRowState.Normal Or e.Row.RowState = DataControlRowState.Alternate Then
            
            If e.Row.Cells(5).Controls.Count <> 0 Then
                
                Dim btndelete As LinkButton = CType(e.Row.Cells(5).Controls(0), LinkButton)
                
                If btndelete IsNot Nothing Then
                   
                    btndelete.Attributes("onclick") = "return confirm('您确定要删除该记录吗?')"
                   
                End If
                
            End If
            
        End If
        
    End Sub

解决方案 »

  1.   

    错误信息很明显:无法将类型为“System.Web.UI.LiteralControl”的对象强制转换为类型“System.Web.UI.WebControls.LinkButton”。e.Row.Cells(5).Controls(0)返回的是一个LiteralControl而不是LinkButton, 应该是你的序号有问题,检查一下.
      

  2.   

    控件找错了,估计是列不对,也有可能是Controls[n]中的n不正确
      

  3.   

    你的第6列是什么控件?是不是有多个 Dim btndelete As LinkButton = CType(e.Row.Cells(5).Controls(1), LinkButton) 
      

  4.   

    Control[1]才是你要找的位置,0是Text的位置
      

  5.   

    你可以用程序调一下第几个控件是LinkButton类型,这个提示肯定标示你的控件错了,
      

  6.   

    你的代码没有测试,我想问题有几个
    1、在rowdatabound事件处理比较好
    2、最好用e.row.findcontrol("控件名")的方式以下代码可用
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim lb As LinkButton
                lb = e.Row.FindControl("LinkButton1")
                If DataBinder.Eval(e.Row.DataItem, "Status") < 5 Then
                    lb.Attributes.Add("onclick", "javascript:return confirm('您准备删除这条记录吗?')")
                Else
                    lb.Attributes.Add("onclick", "javascript:return alert('不能删除此记录!')")
                End If
            End If
        End Sub