How to get value from selecteditem in DataGrid

zleug 61 Reputation points
2020-09-13T23:25:05.597+00:00

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.

Thanks.

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,185 questions
No comments
{count} votes

Accepted answer
  1. DaisyTian-1203 11,506 Reputation points
    2020-09-14T01:47:41.54+00:00

    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:

     <StackPanel>  
            <DataGrid x:Name="dataGrid" ItemsSource="{Binding }" AutoGenerateColumns="False"  SelectionMode="Extended" SelectionUnit="FullRow"  SelectedCellsChanged="dataGrid_SelectedCellsChanged">  
                <DataGrid.Columns>  
                    <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}"/>  
                </DataGrid.Columns>  
            </DataGrid>  
            <TextBlock>selected Items</TextBlock>  
            <TextBlock Width="600" Height="200" Name="myTxt" TextWrapping="Wrap" VerticalAlignment="Bottom" HorizontalAlignment="Left"> </TextBlock>  
        </StackPanel>  
    

    The code for MainWindow.xaml.cs:

    public partial class MainWindow : Window  
        {  
            public MainWindow()  
            {  
                InitializeComponent();  
                ObservableCollection<Member> memberData = new ObservableCollection<Member>()  
                {  
                    new Member(){DepartmetId = "Dp01",EmployeeId = "EP0011" ,Name = "Joe1",Address = "Street 1",Email = new Uri("mailto:Joe1@school.com")},  
                    new Member(){DepartmetId = "Dp02",EmployeeId = "EP0012" ,Name = "Joe2",Address = "Street 2",Email = new Uri("mailto:Joe2@school.com")},  
                    new Member(){DepartmetId = "Dp03",EmployeeId = "EP0013" ,Name = "Joe3",Address = "Street 3",Email = new Uri("mailto:Joe3@school.com")},  
                    new Member(){DepartmetId = "Dp04",EmployeeId = "EP0014" ,Name = "Joe4",Address = "Street 4",Email = new Uri("mailto:Joe4@school.com")}  
                };  
                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";  
                    }  
                }  
                else  
                {  
      
                }  
                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:
    24322-4.gif

    No comments

2 additional answers

Sort by: Most helpful
  1. Peter Fleischer (Freelancer) 17,571 Reputation points
    2020-09-14T03:41:48.707+00:00

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

    XAML:

    <Window x:Class="WpfApp1.Window81"  
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
            xmlns:local="clr-namespace:WpfApp81"  
            mc:Ignorable="d"  
            Title="Window81" Height="450" Width="800">  
      <Window.DataContext>  
        <local:ViewModel/>  
      </Window.DataContext>  
      <Grid>  
        <Grid.RowDefinitions>  
          <RowDefinition/>  
          <RowDefinition Height="Auto"/>  
        </Grid.RowDefinitions>  
        <DataGrid ItemsSource="{Binding View}">  
          <DataGrid.Columns>  
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>  
            <DataGridTextColumn Header="Address" Binding="{Binding Address}"/>  
            <DataGridTextColumn Header="Email" Binding="{Binding Email}"/>  
          </DataGrid.Columns>  
        </DataGrid>  
        <Label Grid.Row="1" Content="{Binding Detail.EmployeeId}"/>  
      </Grid>  
    </Window>  
    

    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  
        {  
          get  
          {  
            if (cvs.Source == null)  
            {  
              GetData();  
              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("mailto:Joe1@school.com")},  
                     new Data(){DepartmetId = "Dp02",EmployeeId = "EP0012" ,Name = "Joe2",Address = "Street 2",Email = new Uri("mailto:Joe2@school.com")},  
                     new Data(){DepartmetId = "Dp03",EmployeeId = "EP0013" ,Name = "Joe3",Address = "Street 3",Email = new Uri("mailto:Joe3@school.com")},  
                     new Data(){DepartmetId = "Dp04",EmployeeId = "EP0014" ,Name = "Joe4",Address = "Street 4",Email = new Uri("mailto:Joe4@school.com")}  
                 };  
          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; }  
      }  
    }  
    

    24392-x.gif

    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  
          Get  
            If cvs.Source Is Nothing Then  
              GetData()  
              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  
          Get  
            Return Me._detail  
          End Get  
          Set(value As Data)  
            Me._detail = value  
            OnPropertyChanged()  
          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("mailto:Joe1@school.com")})  
          col.Add(New Data() With {.DepartmetId = "Dp02", .EmployeeId = "EP0012", .Name = "Joe2", .Address = "Street 2", .Email = New Uri("mailto:Joe2@school.com")})  
          col.Add(New Data() With {.DepartmetId = "Dp03", .EmployeeId = "EP0013", .Name = "Joe3", .Address = "Street 3", .Email = New Uri("mailto:Joe3@school.com")})  
          col.Add(New Data() With {.DepartmetId = "Dp04", .EmployeeId = "EP0014", .Name = "Joe4", .Address = "Street 4", .Email = New Uri("mailto:Joe4@school.com")})  
          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  
    
    No comments

  2. Christian 6 Reputation points
    2022-12-24T23:50:03.18+00:00

    I should appreciate same example for Visual Basic.

    No comments