保持在gridview问题中选择所选项目

时间:2022-01-14 18:59:28

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.

我试图在选择任何操作(如排序)后选择的gridview中保留所选项(datakey)。我有保持选中的代码,但有时项目的最后位置(排序前的索引)仍然被选中,以及所选项目的新索引。

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!

为什么选择多个项目?我知道ProductID对每个产品都是独一无二的。谢谢!

1 个解决方案

#1


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.

Harv是对的,谢谢你的评论。我实际上有一些错误的代码遗留在我试图在RowDataBound(这不起作用,不要在那里做)这导致问题的地方。我以为我删除了它,但我猜不是。

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

谢谢,良好的直觉! (发布作为答案,如果你想要Harv,我会把它标记为正确)

#1


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.

Harv是对的,谢谢你的评论。我实际上有一些错误的代码遗留在我试图在RowDataBound(这不起作用,不要在那里做)这导致问题的地方。我以为我删除了它,但我猜不是。

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

谢谢,良好的直觉! (发布作为答案,如果你想要Harv,我会把它标记为正确)