How to get value from selecteditem in DataGrid

zleug 61 Reputation points

Hi All.
In WPF form I would like to get one of value of selected DataGrid item. That value not presented in DataGrid columns. What I mean. For instance, DataGrid has columns:
Name | Address | Email
The data source of DataGrid has columns:
EmployeeId | DepartmetId | Name | Address | Email

How to get the DepartmentId value? I will appreciate for sample and explanation.


Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,274 questions
No comments
{count} votes

Accepted answer
  1. DaisyTian-1203 11,506 Reputation points

    You can set Visibility="Hidden" for the EmployeeId and DepartmetId columns. I will show you a sample of this.
    The code for my MainWindow.xaml:

            <DataGrid x:Name="dataGrid" ItemsSource="{Binding }" AutoGenerateColumns="False"  SelectionMode="Extended" SelectionUnit="FullRow"  SelectedCellsChanged="dataGrid_SelectedCellsChanged">  
                    <DataGridTextColumn Visibility="Hidden" Header="DepartmetId" Width="80" Binding="{Binding DepartmetId}"/>  
                    <DataGridTextColumn Visibility="Hidden" Header="EmployeeId" Width="80" Binding="{Binding EmployeeId}"/>  
                    <DataGridTextColumn Header="Name" Width="80" Binding="{Binding Name}"/>  
                    <DataGridTextColumn Header="Address" Width="50" Binding="{Binding Address}" />  
                    <DataGridHyperlinkColumn Header="Email" Width="150"   Binding="{Binding Email}"/>  
            <TextBlock>selected Items</TextBlock>  
            <TextBlock Width="600" Height="200" Name="myTxt" TextWrapping="Wrap" VerticalAlignment="Bottom" HorizontalAlignment="Left"> </TextBlock>  

    The code for MainWindow.xaml.cs:

    public partial class MainWindow : Window  
            public MainWindow()  
                ObservableCollection<Member> memberData = new ObservableCollection<Member>()  
                    new Member(){DepartmetId = "Dp01",EmployeeId = "EP0011" ,Name = "Joe1",Address = "Street 1",Email = new Uri("")},  
                    new Member(){DepartmetId = "Dp02",EmployeeId = "EP0012" ,Name = "Joe2",Address = "Street 2",Email = new Uri("")},  
                    new Member(){DepartmetId = "Dp03",EmployeeId = "EP0013" ,Name = "Joe3",Address = "Street 3",Email = new Uri("")},  
                    new Member(){DepartmetId = "Dp04",EmployeeId = "EP0014" ,Name = "Joe4",Address = "Street 4",Email = new Uri("")}  
                dataGrid.DataContext = memberData;  
            private void dataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)  
                string str = "";  
                if (dataGrid.SelectedItems.Count > 0)  
                    Member member = new Member();  
                    foreach (var obj in dataGrid.SelectedItems)  
                        member = obj as Member;  
                        str += "DepartmetId : " + member.DepartmetId + "   EmployeeId:" + member.EmployeeId + "  Name:" + member.Name + "  Address:" + member.Address + "  Email:" + member.Email + "\n";  
                myTxt.Text = str;  
        public class Member  
            public string EmployeeId { get; set; }  
            public string DepartmetId { get; set; }        
            public string Name { get; set; }  
            public string Address { get; set; }  
            public Uri Email { get; set; }  

    The picture of testing:

2 additional answers

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 18,371 Reputation points

    another approach is to use ObservableCollection and CurrentChanged to get CurrentItem. Try following MVVM demo:


    <Window x:Class="WpfApp1.Window81"  
            Title="Window81" Height="450" Width="800">  
          <RowDefinition Height="Auto"/>  
        <DataGrid ItemsSource="{Binding View}">  
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>  
            <DataGridTextColumn Header="Address" Binding="{Binding Address}"/>  
            <DataGridTextColumn Header="Email" Binding="{Binding Email}"/>  
        <Label Grid.Row="1" Content="{Binding Detail.EmployeeId}"/>  

    and ViewModel: and Data class

    using System;  
    using System.Collections.ObjectModel;  
    using System.ComponentModel;  
    using System.Runtime.CompilerServices;  
    using System.Windows;  
    using System.Windows.Data;  
    namespace WpfApp81  
      public class ViewModel : INotifyPropertyChanged  
        private CollectionViewSource cvs = new CollectionViewSource();  
        private ObservableCollection<Data> col;  
        public ICollectionView View  
            if (cvs.Source == null)  
              cvs.View.CurrentChanged += (sender, e) => Detail = cvs.View.CurrentItem as Data;  
            return cvs.View;  
        private Data _detail = null;  
        public Data Detail { get => this._detail; set { this._detail = value; OnPropertyChanged(); } }  
        private void GetData()  
          col = new ObservableCollection<Data>()  
                     new Data(){DepartmetId = "Dp01",EmployeeId = "EP0011" ,Name = "Joe1",Address = "Street 1",Email = new Uri("")},  
                     new Data(){DepartmetId = "Dp02",EmployeeId = "EP0012" ,Name = "Joe2",Address = "Street 2",Email = new Uri("")},  
                     new Data(){DepartmetId = "Dp03",EmployeeId = "EP0013" ,Name = "Joe3",Address = "Street 3",Email = new Uri("")},  
                     new Data(){DepartmetId = "Dp04",EmployeeId = "EP0014" ,Name = "Joe4",Address = "Street 4",Email = new Uri("")}  
          cvs.Source = col;  
        public event PropertyChangedEventHandler PropertyChanged;  
        private void OnPropertyChanged([CallerMemberName] String propertyName = "") =>  
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
      public class Data  
        public string EmployeeId { get; set; }  
        public string DepartmetId { get; set; }  
        public string Name { get; set; }  
        public string Address { get; set; }  
        public Uri Email { get; set; }  


    And classes in VB.NET:

      Public Class ViewModel  
        Implements INotifyPropertyChanged  
        Private cvs As New CollectionViewSource()  
        Private col As ObservableCollection(Of Data)  
        Public ReadOnly Property View As ICollectionView  
            If cvs.Source Is Nothing Then  
              AddHandler cvs.View.CurrentChanged, Sub()  
                                                    Detail = TryCast(cvs.View.CurrentItem, Data)  
                                                  End Sub  
            End If  
            Return cvs.View  
          End Get  
        End Property  
        Private _detail As Data = Nothing  
        Public Property Detail As Data  
            Return Me._detail  
          End Get  
          Set(value As Data)  
            Me._detail = value  
          End Set  
        End Property  
        Private Sub GetData()  
          col = New ObservableCollection(Of Data)  
          col.Add(New Data() With {.DepartmetId = "Dp01", .EmployeeId = "EP0011", .Name = "Joe1", .Address = "Street 1", .Email = New Uri("")})  
          col.Add(New Data() With {.DepartmetId = "Dp02", .EmployeeId = "EP0012", .Name = "Joe2", .Address = "Street 2", .Email = New Uri("")})  
          col.Add(New Data() With {.DepartmetId = "Dp03", .EmployeeId = "EP0013", .Name = "Joe3", .Address = "Street 3", .Email = New Uri("")})  
          col.Add(New Data() With {.DepartmetId = "Dp04", .EmployeeId = "EP0014", .Name = "Joe4", .Address = "Street 4", .Email = New Uri("")})  
          cvs.Source = col  
        End Sub  
        Private Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged  
        Private Sub OnPropertyChanged(<CallerMemberName> Optional propertyName As String = "")  
          RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))  
        End Sub  
      End Class  
      Public Class Data  
        Public Property EmployeeId As String  
        Public Property DepartmetId As String  
        Public Property Name As String  
        Public Property Address As String  
        Public Property Email As Uri  
      End Class  
    1 person found this answer helpful.
    No comments

  2. Christian 6 Reputation points

    I should appreciate same example for Visual Basic.