Search code examples
wpfwpfdatagrid

Datagrid text search


I want to search a text in the datagrid, A code written like below gives error

For i As Integer = 0 To _dt.Items.Count - 1
            Dim row As DataGridRow = DirectCast(_dt.ItemContainerGenerator.ContainerFromIndex(i), DataGridRow)
            For j As Integer = 0 To _dt.Columns.Count - 1
                If row IsNot Nothing Then
                    Dim cellContent As TextBlock = TryCast(_dt.Columns(j).GetCellContent(row), TextBlock)
                    If cellContent IsNot Nothing AndAlso cellContent.Text.Equals(txtfind.Text) Then
                        _dt.ScrollIntoView(row, _dt.Columns(j))
                        Dim presenter As DataGridCellsPresenter = GetVisualChild(Of DataGridCellsPresenter(row))
                        Dim cell As DataGridCell = DirectCast(presenter.ItemContainerGenerator.ContainerFromIndex(j), DataGridCell)
                        _dt.SelectedItem = cell
                        cell.IsSelected = True
                        row.MoveFocus(New TraversalRequest(FocusNavigationDirection.[Next]))
                        Exit For
                    End If
                End If
            Next
        Next

Error is for row : Array bounds cannot appear in type specifiers. Statement: Dim presenter As DataGridCellsPresenter = GetVisualChild(Of DataGridCellsPresenter(row))

Help appreciated abhimoh


Solution

  • Change:

       Dim presenter As DataGridCellsPresenter = GetVisualChild(Of DataGridCellsPresenter(row))
    
    'you have created an array with row number of values.
    

    to:

       Dim presenter As DataGridCellsPresenter = GetVisualChild(Of DataGridCellsPresenter)(row)