views:

420

answers:

1

I am trying to keep the selected item (datakey) in a gridview selected after any operation, such as sorting. I have code that is keeping it selected, but sometimes the item's last position (index before it was sorted) remains selected, along with the new index for the selected item.

Any time it is selected, that item is bound to a details view, which I am using to read the value back. Here is the code, any help is appreciated! Thanks

    Private Sub ProductsGridView_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles ProductsGridView.DataBound

    Dim Row As GridViewRow
    Dim SelectedValue As String = ProductDetailsView.DataKey("ProductID")
    If SelectedValue Is Nothing Then
        Return
    End If

    ' Determine if the selected row is visible and re-select it
    For Each Row In ProductsGridView.Rows
        Dim KeyValue As String = ProductsGridView.DataKeys(Row.RowIndex)("ProductID")
        If (KeyValue = SelectedValue) Then
            ProductsGridView.SelectedIndex = Row.RowIndex
        End If
    Next

End Sub

Why is this selecting multiple items? I know the ProductIDs are unique to every product. Thanks!

A: 

Harv was right, thanks for the comment. I actually had some buggy code left over where I was trying to do this in RowDataBound (which doesn't work, don't do it there) which was causing the issue. I thought I had deleted it but it I guess not.

Thanks, good intuition! (Post that as an answer and I'll mark it right if you want Harv)

Ryan