locked
Get row id in ListView ItemTemplate RRS feed

  • Question

  • User1510859543 posted

    I am trying to get the record ID from a row inside a ListView ItemTemplate with the following markup and code but keep getting the following error on the code.

    Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlTableCell' to type 'System.Web.UI.WebControls.ListViewDataItem'.

    Below is the markup and code affected.  It is failing on the 2nd line of the Sub.

       <asp:CheckBox ID="ckComplete" runat="server" Checked='<%# Eval("Complete") %>' 
              AutoPostBack="True" OnCheckedChanged="ckComplete_CheckedChanged" />
     
    
       Protected Sub ckComplete_CheckedChanged(sender As Object, e As EventArgs)
            Dim ck As CheckBox = CType(sender, CheckBox)
            Dim lvitem As ListViewDataItem = CType(ck.Parent, ListViewDataItem)
            'get the TaskID value from this row
            Dim strTaskID As String = DirectCast(lvitem.FindControl("LblTaskID"), Label).Text
            Dim strSQL As String = ""
    
    	update code here...
    
            lvTasksOpen.DataBind()
        End Sub
    

     

    Thursday, July 20, 2017 2:17 PM

Answers

  • User2103319870 posted

    Dim lvitem As ListViewDataItem = CType(ck.Parent, ListViewDataItem)

    Try finding out the control from container instead of Parent like below

    Protected Sub ckComplete_CheckedChanged(sender As Object, e As EventArgs)
            Dim ck As CheckBox = CType(sender, CheckBox)
            'Instead of parent use NamingContainer
            Dim lvitem As ListViewDataItem = CType(ck.NamingContainer, ListViewDataItem)
            'get the TaskID value from this row
            Dim strTaskID As String = DirectCast(lvitem.FindControl("LblTaskID"), Label).Text
            Dim strSQL As String = ""
    
            'update code here...
    
            'lvTasksOpen.DataBind()
        End Sub

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 20, 2017 2:26 PM