logo MSJO.kr

WPF Datagrid Get Selected Cell Value

2019-08-27
MsJ
   

이번 글은 WPF Datagrid를 사용할 때 선택한 Row에서 각 Column 값을 가져오는 예제이다. 아래 소스는 클래스 모델(Database라고 가정)을 그리드에 바인딩하고 Cell 안의 버튼 이벤트와 Row 선택 이벤트를 어떻게 작성하는지 보여준다.

데이터 모델
using System.Collections.ObjectModel;

namespace WPFDB
{
    public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public static ObservableCollection<Student> GetStudent()
        {
            var student = new ObservableCollection<Student>
            {
                new Student() { ID = 100, Name = "가나닭-abc" },
                new Student() { ID = 200, Name = "마바삵-ABC" }
            };
            return student;
        }
    }
}
MainWindow.xaml
<Window x:Class="WPFDB.MainWindow"
        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:WPFDB"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <DataGrid x:Name="GridStudent" AutoGenerateColumns="False" CanUserAddRows="False" IsReadOnly="True" SelectionUnit="FullRow">
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button x:Name="BtnDetailView" Content="Detail" Click="BtnDetailView_Click" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    <DataGridTextColumn Header="아이디" Binding="{Binding ID}" />
                    <DataGridTextColumn Header="이름" Binding="{Binding Name}" />
                </DataGrid.Columns>
            </DataGrid>
            <TextBox x:Name="TxtBoxID" Text="{Binding SelectedItem.ID, ElementName=GridStudent, Mode=OneWay}" />
            <TextBox x:Name="TxtBoxName" Text="{Binding SelectedItem.Name, ElementName=GridStudent, Mode=OneWay}" />
        </StackPanel>
    </Grid>
</Window>
MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;

namespace WPFDB
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            GridStudent.ItemsSource = Student.GetStudent();

            GridStudent.SelectedCellsChanged += (s, e) =>
            {
                var dg = s as DataGrid;
                var t1 = dg.Columns[1].GetCellContent(dg.SelectedItem) as TextBlock;
                var t2 = dg.Columns[2].GetCellContent(dg.SelectedItem) as TextBlock;
                MessageBox.Show($"RowClick : {t1.Text} : {t2.Text}");
            };
        }

        private void BtnDetailView_Click(object sender, RoutedEventArgs e)
        {
            Student student = GridStudent.SelectedItem as Student;
            string studentID = student.ID.ToString();
            string studentName = student.Name;
            MessageBox.Show($"ButtonClick : {studentID} : {studentName}");
        }
    }
}
WPF DataGrid - Selection Mode
  • SelectionMode = “Single/Extended”
  • SelectionUnit = “Cell/FullRow(Default)/CellOrRowHeader”
  • Methods : SelectAll(), UnselectAll(), SelectAllCells(), UnselectAllCells()
  • Options : SelectedItem, SelectedItems, SelectedCells
Reference

Prεv   Nεxt
Content
Search     RSS Feed     BY-NC-ND