views:

6938

answers:

1

I'm converting functionality from an asp.net Gridview to a Listview. In the gridview when the selected item changed I would grab a value from a label in the selected row and write it to a different label outside of the gridview.

Protected Sub grdModules_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdModules.SelectedIndexChanged

    Dim lblModuleTitle As Label = grdModules.SelectedRow.FindControl("lblModuleTitle")
    lblCurrentModule.Text = lblModuleTitle.Text

End Sub

In a Listview, there isn't a "SelectedRow" concept but a SelectedItem. However you can't do findcontrol against the selected item. When I try to do the following (I get a null reference exception):

Protected Sub listviewModules_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles listviewModules.SelectedIndexChanged

    Dim lblModuleTitle As Label = CType(listviewModules.FindControl("lblModuleTitle"), Label)
    lblCurrentModule.Text = lblModuleTitle.Text

End Sub

Does anyone know the way to find a control inside the selected item template?

+3  A: 

You're calling FindControl on the whole ListView, rather than just the selected item. This should work:

Dim lblModuleTitle As Label = CType(listviewModules.Items(listviewModules.SelectedIndex).FindControl("lblModuleTitle"), Label)
stevemegson
You are correct with after syntax change (if you want to update your post):Dim lblModuleTitle As Label = CType(listviewModules.Items(listviewModules.SelectedIndex).FindControl("lblModuleTitle"), Label)thanks!
theminesgreg
One other thing to note: I struggled with this forever -- make sure you have the item you're trying to find in both the ItemTemplate and the SelectedItem template. It won't find it unless it's in both.
theminesgreg
Fixed - is it very obvious that I normally live in C# land?
stevemegson