Results 1 to 14 of 14

Thread: Get Value from DataGrid Cell (WPF)

  1. #1

    Thread Starter
    New Member
    Join Date
    Oct 2016
    Posts
    8

    Get Value from DataGrid Cell (WPF)

    I am looking for a way to read the value of allways one specific cell (Row:0, Column 2) in a DataGrid.

    In WinForms it was very easy:

    var1 = DataGridView1.Item(2, 0).Value
    I am searching for hours now without finding anything usefull. It is important that I can choose values programatically, like in the way above, without preselections with mouse etc.

    I hope someone knows an answer to that

    Regards

  2. #2
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: Get Value from DataGrid Cell (WPF)

    Hello,

    Welcome to the forums!

    To get the cell value of winforms datagridview is straightforward. In WPF, you need to access the Visual Tree (hierarchy of elements) of the datagrid down to
    the datagridcell.

    Download the project in my codebank submission: Accessing Rows and Cells in a WPF DataGrid and put the code below inside the SetColorCell() method.

    VB.NET Code:
    1. Dim cell As DataGridCell = TryCast(grid1.Columns(1).GetCellContent(grid1.GetRow(0)).Parent, DataGridCell)
    2. Dim name As String = TryCast(cell.Content, TextBlock).Text
    3. MessageBox.Show(name)

    Note: The code above, retrieves the cell value in row 0 column 1.

    - kgc
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

  3. #3

    Thread Starter
    New Member
    Join Date
    Oct 2016
    Posts
    8

    Re: Get Value from DataGrid Cell (WPF)

    Thank you for this solution kgc,

    isn't there a simpler way? - 300+ lines of code vs. 1, this just shouldn 't be.

    omega

  4. #4
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: Get Value from DataGrid Cell (WPF)

    isn't there a simpler way? - 300+ lines of code vs. 1, this just shouldn 't be.
    If you browse and debug through the code, you only need this function in order for the code in post #2 to work.

    VB.NET Code:
    1. <Extension()>
    2.     Function GetRow(ByVal grid As DataGrid, ByVal index As Integer) As DataGridRow
    3.  
    4.         Dim row As DataGridRow = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
    5.         If row Is Nothing Then
    6.             grid.UpdateLayout()
    7.             grid.ScrollIntoView(grid.Items(index))
    8.             row = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
    9.         End If
    10.  
    11.         Return row
    12.     End Function

    But if you insist on one liner solution, maybe you can do some search in MSDN docs. Maybe you can come up with something.

    By the way, are you binding a DataTable object to the ItemSource of your DataGrid? Or List<T>? Or Observable Collection?

    - kgc
    Last edited by KGComputers; Oct 18th, 2016 at 07:02 AM. Reason: added question on binding
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

  5. #5
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: Get Value from DataGrid Cell (WPF)

    Aha, you can do it in one line. Given that your DataGrid's ItemSource is assigned with a DataTable object and your grid has few number of rows. All of them visible inside the grid.

    VB.NET Code:
    1. Dim namePerson = TryCast(grid1.Items(0), DataRowView).Row.Item(1).ToString()
    2. MessageBox.Show(namePerson)

    However, the code above might have some issues given that the grid has hundreds of rows and those rows will be visible once
    you scroll through. The one liner code does not have a ScrollIntoView() method applied. So I still prefer using the extension method in post #4.

    - kgc
    Last edited by KGComputers; Oct 18th, 2016 at 07:21 AM.
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

  6. #6

    Thread Starter
    New Member
    Join Date
    Oct 2016
    Posts
    8

    Re: Get Value from DataGrid Cell (WPF)

    Thank you for your effort to help me out on this!

    This is the code from you I implemented.
    Unfortunatelly I am note able to execute it.


    Error BC30456 "GetRow" is not a member of "DataGrid".

    (bgdatagrid_ArtikelInf.GetRow(0)).Parent, DataGridCell)



    Code:
                
         Private Sub btn_tc1_ENTER_Click(sender As Object, e As RoutedEventArgs) Handles btn_tc1_ENTER.Click
    
                Dim cell As DataGridCell = TryCast(bgdatagrid_ArtikelInf.Columns(2).GetCellContent(bgdatagrid_ArtikelInf.GetRow(0)).Parent, DataGridCell)
                Dim name As String = TryCast(cell.Content, TextBlock).Text
                MessageBox.Show(name)
    
    
            End If
        End Sub
    
        '<Extension()>
        Function GetRow(ByVal grid As DataGrid, ByVal index As Integer) As DataGridRow
    
            Dim row As DataGridRow = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
            If row Is Nothing Then
                grid.UpdateLayout()
                grid.ScrollIntoView(grid.Items(index))
                row = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
            End If
    
            Return row
        End Function

    Omega

  7. #7
    Lively Member homer13j's Avatar
    Join Date
    Nov 2003
    Location
    Where the dirt bikes and ATVs play
    Posts
    80

    Re: Get Value from DataGrid Cell (WPF)

    Quote Originally Posted by Omega123 View Post
    Error BC30456 "GetRow" is not a member of "DataGrid".


    Code:
                
        '<Extension()>
    Your Extension attribute is commented out. Remove the apostrophe and it should work.
    "Bones heal. Chicks dig scars. Pain is temporary. Glory is forever." - Robert Craig "Evel" Knievel
    “Leave me alone, I know what I’m doing.” - Kimi Raikkonen

  8. #8
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: Get Value from DataGrid Cell (WPF)

    And make sure to import CompilerServices namespace.

    VB.NET Code:
    1. Imports System.Runtime.CompilerServices
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

  9. #9

    Thread Starter
    New Member
    Join Date
    Oct 2016
    Posts
    8

    Re: Get Value from DataGrid Cell (WPF)

    Good morning,

    - the code I posted above is in MainWindow.xaml.vb
    - The name of my DataGrid = bgdatagrid_ArtikelInf
    - Imports System.Runtime.CompilerServices is above the class in MainWindow.xaml.vb
    - <Extension()> (without apostrophe) I have no clue what this actually does

    - This is the hole code inside MainWindow.xaml.vb


    Private Sub btn_tc1_ENTER_Click(sender As Object, e As RoutedEventArgs) Handles btn_tc1_ENTER.Click
    Me.ArtikelAuftrag = TextBox1.Text

    'MsgBox(ArtikelAuftrag)

    Dim con As String = "Server=FHPCzz\SQLEXPRESS;Database=zzz;User=zzz;Pwd=zzz;"
    Dim connection As New SqlConnection(con)

    If Me.ArtikelAuftrag.Contains("#") Then
    Me.ArtikelAuftrag = Replace(Me.ArtikelAuftrag, "#", "")
    Dim cmd As String = "Select * From ArtikelInf Where ArtikelNr = '" & Me.ArtikelAuftrag & "'"
    Dim command As New SqlCommand(cmd, connection)
    Dim sda As New SqlDataAdapter(command)
    MsgBox("Artikelnummer " & Me.ArtikelAuftrag)
    Try
    connection.Open()
    Dim dt As New DataTable("Employee")
    sda.Fill(dt)
    bgdatagrid_ArtikelInf.ItemsSource = dt.DefaultView
    connection.Close()
    Catch ex As Exception
    MsgBox(ex.toString)
    End Try

    ' hier wird zuerst die AuftragsInformationen ausgelesen, im zweiten schritt die tabelle nach der Artieklnummer gesucht und anschließend die Artikeltabelle gefüllt.
    Else
    Dim cmd As String = "Select * From AuftragInf Where BetriebsAuftragsNr = '" & Me.ArtikelAuftrag & "'"
    Dim command As New SqlCommand(cmd, connection)
    Dim sda As New SqlDataAdapter(command)
    MsgBox("Auftragsnummer " & Me.ArtikelAuftrag)
    Try
    connection.Open()
    Dim dt As New DataTable("Employee")
    sda.Fill(dt)
    bgdatagrid_AuftragInf.ItemsSource = dt.DefaultView
    connection.Close()
    'Dim x As String = bgdatagrid_AuftragInf.


    Catch ex As Exception
    MsgBox(ex.ToString)
    End Try

    Try
    'MsgBox(bgdatagrid_AuftragInf.CurrentCell.Item(2, 0).Value)

    Dim cmd2 As String = "Select * From ArtikelInf Where ArtikelNr = '" & bgdatagrid_AuftragInf.CurrentCell.Item(2, 0).Value & "'"
    Dim command2 As New SqlCommand(cmd, connection)
    Dim sda2 As New SqlDataAdapter(command)
    connection.Open()
    Dim dt2 As New DataTable("Employee")
    sda2.Fill(dt2)
    bgdatagrid_ArtikelInf.ItemsSource = dt2.DefaultView
    connection.Close()


    Catch ex As Exception

    End Try


    Dim cell As DataGridCell = TryCast(bgdatagrid_ArtikelInf.Columns(2).GetCellContent(Grid.GetRow(0)).Parent, DataGridCell)
    Dim name As String = TryCast(cell.Content, TextBlock).Text
    MessageBox.Show(name)


    End If
    End Sub

    <Extension()>
    Function GetRow(ByVal grid As DataGrid, ByVal index As Integer) As DataGridRow

    Dim row As DataGridRow = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
    If row Is Nothing Then
    grid.UpdateLayout()
    grid.ScrollIntoView(grid.Items(index))
    row = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
    End If

    Return row
    End Function

    VS throws two errors marked in RED so no compiling is posible:


    ERROR BC36551 extended methods can only be defined in Modules

    ERROR BC30311 The Value of type "Integer" can not be converted into "UIElement"




    Omega

  10. #10
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: Get Value from DataGrid Cell (WPF)

    ERROR BC36551 extended methods can only be defined in Modules
    Create an empty module in your project called DataGridExtensions and transfer the GetRow() function from MainWindow.Xaml.vb to DataGridExtensions.vb module just like in my example project.

    VB.NET Code:
    1. Imports System.Runtime.CompilerServices
    2.  
    3. Module DataGridExtensions
    4.  
    5.   <Extension()>
    6.     Function GetRow(ByVal grid As DataGrid, ByVal index As Integer) As DataGridRow
    7.  
    8.         Dim row As DataGridRow = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
    9.         If row Is Nothing Then
    10.             grid.UpdateLayout()
    11.             grid.ScrollIntoView(grid.Items(index))
    12.             row = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
    13.         End If
    14.  
    15.         Return row
    16.     End Function
    17.  
    18. End Module

    ERROR BC30311 The Value of type "Integer" can not be converted into "UIElement"
    Your using the Grid class "Grid.GetRow(0)" instead of your grid object when referencing GetRow() method which is wrong. Replace it with your grid object such as below:

    vb.net Code:
    1. Dim cell As DataGridCell = TryCast(bgdatagrid_ArtikelInf.Columns(2).GetCellContent(bgdatagrid_ArtikelInf.GetRow(0)).Parent, DataGridCell)
    Last edited by KGComputers; Oct 19th, 2016 at 12:58 AM.
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

  11. #11

    Thread Starter
    New Member
    Join Date
    Oct 2016
    Posts
    8

    Re: Get Value from DataGrid Cell (WPF)

    ok we are getting somewhere,

    no errors before execution, but when I run the application I get the following:

    Zusätzliche Informationen: Der Index lag außerhalb des Bereichs. Er darf nicht negativ und kleiner als die Auflistung sein.
    (translation: The index is out of the range. I shouldn't be negative or smaller than the list)

    I tried to change the indices but no luck with that.
    Last edited by Omega123; Oct 19th, 2016 at 02:01 AM.

  12. #12
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: Get Value from DataGrid Cell (WPF)

    Trace and debug your code. It must have something to do with datagrid's databinding. It could be that the datagrid has no rows at all when you access the row and column.

    -kgc
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

  13. #13

    Thread Starter
    New Member
    Join Date
    Oct 2016
    Posts
    8

    Re: Get Value from DataGrid Cell (WPF)

    yuhuuuu! Its working!,
    thank you very much!!

    there is one little issue left - the datagrid is on a different tab. That means to only way to get the value of the specific cell is to run your function when you are on the same tab as the datagrid.
    Otherwise it throws the exception in my last post.

    Is there a way around this?

    Thank you again

  14. #14
    Frenzied Member KGComputers's Avatar
    Join Date
    Dec 2005
    Location
    Cebu, PH
    Posts
    2,020

    Re: Get Value from DataGrid Cell (WPF)

    Maybe you can do some readings on how to navigate through the Tab's Visual Tree to access the DataGrid object. Just like the method GetVisualChild() in DataGridExtensions.vb from post #2.
    CodeBank: VB.NET & C#.NET | ASP.NET
    Programming: C# | VB.NET
    Blogs: Personal | Programming
    Projects: GitHub | jsFiddle
    ___________________________________________________________________________________

    Rating someone's post is a way of saying Thanks...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width