locked
Selected item from DataGrid RRS feed

  • Question

  • I have a data grid filled with records.  I now want to click the record and grab that selected records values and write them to variables....Using the SelectionChanged evetn of the DataGrid I can do this and return the index number of the receord selected but am having a hard tiem grabbing the attributes from that selected record...

    Any thoughts?  THanks


        Private Sub DataGridSelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)

            Dim dataGrid As DataGrid = TryCast(sender, DataGrid)
            Dim selectedIndex As Integer = dataGrid1.SelectedIndex
            MessageBox.Show(selectedIndex)

    Friday, July 1, 2011 4:26 PM

Answers

  • You have to cast it back to the datatype that you bind your datagrid to. If your datagrid bind to a list of MyClass objects then you need to cast it back to that. Ex: Dim obj as MyClass = Ctype(datagrid.SelectedItem, MyClass)

    Friday, July 1, 2011 5:24 PM
  • Hi,

    What is MYClass?

    According to your description ,as other community members mentioned that please convert the DataGrid.SelectedItem object to the datatype which is used to bind data to the DataGrid control:

    You have to cast it back to the datatype that you bind your datagrid to. If your datagrid bind to a list of MyClass objects then you need to cast it back to that. Ex: Dim obj as MyClass = Ctype(datagrid.SelectedItem, MyClass)

    My question is how do I get that returned value to a variable

    I would like to suggest you to check the complete sample:

    1.Code in page(.xaml file):

     <Grid x:Name="LayoutRoot" Background="White">
            <sdk:DataGrid AutoGenerateColumns="True" Name="DataGird1" Width="300" Height="300" SelectionChanged="DataGird1_SelectionChanged" />
        </Grid>

    2.Code in page(.xaml.cs file):

    Partial Public Class GetSelectedItemSample
        Inherits UserControl
        Public Sub New()
            InitializeComponent()
            AddHandler Me.Loaded, AddressOf Page_Loaded
        End Sub
        Private Sub Page_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Me.DataGird1.ItemsSource = SelectedItemSampleGridData.GetData()
        End Sub
    
        Private Sub DataGird1_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
            Dim datagrid As DataGrid = DirectCast(sender, DataGrid)
    
            ' Here the SelectedItemSampleGridData class is the MyClass as other community member mentioned.
            Dim item As SelectedItemSampleGridData = DirectCast(datagrid.SelectedItem, SelectedItemSampleGridData)
    
            ' Set value to variables as you want.
            Dim id As String = item.id.ToString()
            Dim info1 As String = item.Info1
            Dim info2 As String = item.Info2
            MessageBox.Show(String.Format("Selected item:{3} id:{0} {3} Info1:{1} {3} Info2:{2}", id, info1, info2, vbCr & vbLf))
        End Sub
    End Class
    
    Public Class SelectedItemSampleGridData
        Public Property id() As Integer
            Get
                Return m_id
            End Get
            Set(ByVal value As Integer)
                m_id = value
            End Set
        End Property
        Private m_id As Integer
        Public Property Info1() As String
            Get
                Return m_Info1
            End Get
            Set(ByVal value As String)
                m_Info1 = value
            End Set
        End Property
        Private m_Info1 As String
        Public Property Info2() As String
            Get
                Return m_Info2
            End Get
            Set(ByVal value As String)
                m_Info2 = value
            End Set
        End Property
        Private m_Info2 As String
        Public Shared Function GetData() As ObservableCollection(Of SelectedItemSampleGridData)
            Dim data As New ObservableCollection(Of SelectedItemSampleGridData)()
            data.Add(New SelectedItemSampleGridData() With {
              .id = 1,
              .Info1 = "Row1_Info1",
              .Info2 = "Row1_Info2"
            })
            data.Add(New SelectedItemSampleGridData() With {
              .id = 2,
              .Info1 = "Row2_Info1",
              .Info2 = "Row2_Info2"
            })
            data.Add(New SelectedItemSampleGridData() With {
              .id = 3,
              .Info1 = "Row3_Info1",
              .Info2 = "Row3_Info2"
            })
            Return data
        End Function
    End Class

    Please do not forget the reference namespace:

    Imports System.Collections.ObjectModel

    Hope it can help you.

    Wednesday, July 6, 2011 1:40 AM

All replies

  • selecteditem will give you the underlying record.

    Friday, July 1, 2011 4:34 PM
  • I am trying this...but getting weird things....

    Dim Test As String = dataGrid1.SelectedItem.ToString
            MessageBox.Show(Test)

    Im getting single letters on the one below.....

    Dim Test As String = dataGrid1.SelectedItem.ToString(2)
            MessageBox.Show(Test)

    Thought there might be something like this

    Dim Test As String = dataGrid1.SelectedItem.Field(1)
            MessageBox.Show(Test)

    Friday, July 1, 2011 4:42 PM
  • Was also trying this but getting an error on GetParent...not decalred

     Any thoughts....Looking to get the results from multiple fields and usign them...getting them toa message box would be fine...

            If selectedIndex > -1 Then
                Dim findResult As String = DirectCast(dataGrid1.SelectedItem, String)
                Dim column As DataGridColumn = dataGrid1.Columns(0)
                Dim fe As FrameworkElement = column.GetCellContent(dataGrid1.SelectedItem)
                Dim result As FrameworkElement = GetParent(fe, GetType(DataGridCell))

                If result IsNot Nothing Then
                    Dim cell As DataGridCell = DirectCast(result, DataGridCell)
                    'changes the forecolor                
                    cell.Foreground = New SolidColorBrush(Colors.Blue)
                    'how to get cell value?               

                    Dim block As TextBlock = TryCast(fe, TextBlock)
                    If block IsNot Nothing Then
                        Dim cellText As String = block.Text
                        MessageBox.Show(cellText)
                    End If
                End If
            End If

    Friday, July 1, 2011 4:53 PM
  • You have to cast it back to the datatype that you bind your datagrid to. If your datagrid bind to a list of MyClass objects then you need to cast it back to that. Ex: Dim obj as MyClass = Ctype(datagrid.SelectedItem, MyClass)

    Friday, July 1, 2011 5:24 PM
  • I thank you....but not really following....trying here...

    Not really sure what the MyClass is....like this?

    Dim Datagrid As DataGrid = CType(dataGrid1.SelectedItem, DataGrid)

    Then try and get the individual field values from Datagrid?????

    Thanks fro yoru patience....learnign every minute here....if so where do I go from there....

     

    Dim Datagrid As DataGrid = CType(dataGrid1.SelectedItem, DataGrid)
            Dim test2 As String = Datagrid.SelectedItem(3)
            MessageBox.Show(test2)

     

    Friday, July 1, 2011 5:31 PM
  • How do you bind your datagrid?

    Datagrid.Itemsource = ?

    Friday, July 1, 2011 5:39 PM
  • Here is how you can get the selectedItem of the datagrid control

    Public Partial Class Page
    	Inherits UserControl
    	Private _currentSelectedPerson As Person
    
    	Public Sub New()
    		InitializeComponent()
    
    		Dim persons As New List(Of Person)()
    		persons.Add(New Person() With { _
    			Key .Age = 5, _
    			Key .Name = "Tom" _
    		})
    		persons.Add(New Person() With { _
    			Key .Age = 3, _
    			Key .Name = "Lisa" _
    		})
    		persons.Add(New Person() With { _
    			Key .Age = 4, _
    			Key .Name = "Sam" _
    		})
    
    		dg.ItemsSource = persons
    	End Sub
    
    	Private Sub SelectionChanged(sender As Object, e As EventArgs)
    		Dim grid As DataGrid = TryCast(sender, DataGrid)
    		If grid.SelectedItem IsNot Nothing Then
    			_currentSelectedPerson = TryCast(grid.SelectedItem, Person)
    		Else
    			grid.SelectedItem = _currentSelectedPerson
    		End If
    	End Sub
    End Class
    
    Public Class Person
    	Public Property Name() As String
    		Get
    			Return m_Name
    		End Get
    		Set
    			m_Name = Value
    		End Set
    	End Property
    	Private m_Name As String
    	Public Property Age() As Integer
    		Get
    			Return m_Age
    		End Get
    		Set
    			m_Age = Value
    		End Set
    	End Property
    	Private m_Age As Integer
    End Class


    Friday, July 1, 2011 9:13 PM
  • hi,

    try this code

    MYDataGrid.SelectionChanged += new SelectionChangedEventHandler(MYDataGrid_SelectionChanged);

    Implementation of MYDataGrid_SelectionChanged
     
    void MYDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {

                if (MYDataGrid.SelectedItem != null)
                {
      MYClass dataGrigSelectedRow = MYDataGrid.SelectedItem as MYClass;

                    MessageBox.Show(dataGrigSelectedRow.property1)

                }

            } 

    Regards

    Arun

    Saturday, July 2, 2011 2:17 AM
  • Thanks both of you for responding....coupel questions on both solutions...

     

    Arun
    I am tryign to convert this to VB and the converter comes up with errors...
    I like the simplistic code...seems very easy to implement...
    I assume each propperty represents a field
    Oly thing is that I am having issues converting to VB

    What is MYClass?

    MYClass dataGrigSelectedRow = MYDataGrid.SelectedItem as MYClass;
    MessageBox.Show(dataGrigSelectedRow.property1)

    I am trying this but getting errors on property1 is not a memeber of DataGrid

    Dim dataGrigSelectedRow As DataGrid = TryCast(dataGrid1.SelectedItem, DataGrid)
            MessageBox.Show(dataGrigSelectedRow.property1)


    asimsajjad

    My question is how do I get that returned value to a variable
            Private Sub SelectionChanged(sender As Object, e As EventArgs)
                    Dim grid As DataGrid = TryCast(sender, DataGrid)
                    If grid.SelectedItem IsNot Nothing Then
                            _currentSelectedPerson = TryCast(grid.SelectedItem, Record)
                    Else
                            grid.SelectedItem = _currentSelectedPerson
                    End If

                    Dim Test as String = _currentSelectedPerson(ContactID)
            End Sub

        Public Class Record
            Public Property ContactID() As String
                Get
                    Return m_ContactID
                End Get
                Set(ByVal value As String)
                    m_ContactID = value
                End Set
            End Property
            Private m_ContactID As String
        End Class

    Tuesday, July 5, 2011 9:29 AM
  • Hi,

    What is MYClass?

    According to your description ,as other community members mentioned that please convert the DataGrid.SelectedItem object to the datatype which is used to bind data to the DataGrid control:

    You have to cast it back to the datatype that you bind your datagrid to. If your datagrid bind to a list of MyClass objects then you need to cast it back to that. Ex: Dim obj as MyClass = Ctype(datagrid.SelectedItem, MyClass)

    My question is how do I get that returned value to a variable

    I would like to suggest you to check the complete sample:

    1.Code in page(.xaml file):

     <Grid x:Name="LayoutRoot" Background="White">
            <sdk:DataGrid AutoGenerateColumns="True" Name="DataGird1" Width="300" Height="300" SelectionChanged="DataGird1_SelectionChanged" />
        </Grid>

    2.Code in page(.xaml.cs file):

    Partial Public Class GetSelectedItemSample
        Inherits UserControl
        Public Sub New()
            InitializeComponent()
            AddHandler Me.Loaded, AddressOf Page_Loaded
        End Sub
        Private Sub Page_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Me.DataGird1.ItemsSource = SelectedItemSampleGridData.GetData()
        End Sub
    
        Private Sub DataGird1_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
            Dim datagrid As DataGrid = DirectCast(sender, DataGrid)
    
            ' Here the SelectedItemSampleGridData class is the MyClass as other community member mentioned.
            Dim item As SelectedItemSampleGridData = DirectCast(datagrid.SelectedItem, SelectedItemSampleGridData)
    
            ' Set value to variables as you want.
            Dim id As String = item.id.ToString()
            Dim info1 As String = item.Info1
            Dim info2 As String = item.Info2
            MessageBox.Show(String.Format("Selected item:{3} id:{0} {3} Info1:{1} {3} Info2:{2}", id, info1, info2, vbCr & vbLf))
        End Sub
    End Class
    
    Public Class SelectedItemSampleGridData
        Public Property id() As Integer
            Get
                Return m_id
            End Get
            Set(ByVal value As Integer)
                m_id = value
            End Set
        End Property
        Private m_id As Integer
        Public Property Info1() As String
            Get
                Return m_Info1
            End Get
            Set(ByVal value As String)
                m_Info1 = value
            End Set
        End Property
        Private m_Info1 As String
        Public Property Info2() As String
            Get
                Return m_Info2
            End Get
            Set(ByVal value As String)
                m_Info2 = value
            End Set
        End Property
        Private m_Info2 As String
        Public Shared Function GetData() As ObservableCollection(Of SelectedItemSampleGridData)
            Dim data As New ObservableCollection(Of SelectedItemSampleGridData)()
            data.Add(New SelectedItemSampleGridData() With {
              .id = 1,
              .Info1 = "Row1_Info1",
              .Info2 = "Row1_Info2"
            })
            data.Add(New SelectedItemSampleGridData() With {
              .id = 2,
              .Info1 = "Row2_Info1",
              .Info2 = "Row2_Info2"
            })
            data.Add(New SelectedItemSampleGridData() With {
              .id = 3,
              .Info1 = "Row3_Info1",
              .Info2 = "Row3_Info2"
            })
            Return data
        End Function
    End Class

    Please do not forget the reference namespace:

    Imports System.Collections.ObjectModel

    Hope it can help you.

    Wednesday, July 6, 2011 1:40 AM