TonyW
TonyW

Reputation: 786

Reading what row is selected in WPF datagrid

I have a datagrid called "dgvresults", and I add columns to this datagrid in codebehind as follows.

Dim column_selected As New DataGridCheckBoxColumn()
column_selected.Header = "Selected"
column_selected.Binding = New Binding("IsChecked")
dgvResults.Columns.Add(column_selected)

and

Dim column_username As New DataGridTextColumn()
column_username.Header = "User Name"
column_username.Binding = New Binding("UserName")
dgvResults.Columns.Add(column_username)

After this is done, I use this to add rows.

Private Sub run_click(sender As Object, e As RoutedEventArgs)

 For Each item In SearchFunctions.Usersearch
            'addrows(item)

            users.Add(New User With { _
                 .UserName = item
            })

        Next

        dgvResults.ItemsSource = users

 End Sub

The class looks like this

Imports System.ComponentModel


Public Class User

    Implements INotifyPropertyChanged

    Public Property UserName() As String
        Get
            Return m_UserName
        End Get
        Set(value As String)
            m_UserName = value
        End Set
    End Property
    Private m_UserName As String


    Public Property IsChecked() As Boolean
        Get
            Return _IsChecked
        End Get
        Set(value As Boolean)
            _IsChecked = value
            NotifyPropertyChanged("IsChecked")
        End Set
    End Property
    Private _IsChecked As Boolean

    'Public ReadOnly Property Details() As String
    '    Get
    '        Return [String].Format("{0} was born on {1} and this is a long description of the person.", Me.Name, Me.Birthday.ToLongDateString())
    '    End Get
    'End Property

#Region "INotifyPropertyChanged Members"

    Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged

#End Region

#Region "Private Helpers"

    Private Sub NotifyPropertyChanged(propertyName As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

#End Region

End Class

The end result looks a little like this...

enter image description here

What i'm currently having issues with, is figuring out how to find all of the checked items in the datagrid, and read each row, column by column.

Any advice will be helpful!

Thanks!

Upvotes: 0

Views: 116

Answers (2)

TonyW
TonyW

Reputation: 786

Just answered my own question, thanks :)

For Each item In users
    If item.IsChecked Then
        MessageBox.Show(item.UserName)
    End If
Next

Upvotes: 0

Juan Romero
Juan Romero

Reputation: 11

I'm new in stackoverflow :-), not an expert on the subject, but why can't you just iterate over the users(Datasource) list (foreach or using linq) to find the checked ones. The datagrid is only displaying your datasource.

Upvotes: 1

Related Questions