Visual Studio/WPF > DataGrid > 마지막으로 선택한 행 삭제

운영 환경
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community

이하의 실장을 했다.
  • DataGrid에서 선택
  • Delete 버튼을 누릅니다.
  • 선택한 행 지우기


  • lastIndex를 취득하고 있는 이유는, 삭제 버튼을 누른 시점에서 「.SelectedItem」이 보이지 않게 되기 때문.

    참고 : h tps : // s t c ゔ ぇ rf ぉ w. 코 m / 쿠에 s Chion s / 9743420 / Remo ゔ ぇ - an - m-f m an-o bse r ゔ ぁ b 게 d-에 ゔ ぇ

    더 좋은 구현 방법은 있을 것 같다.

    code



    MainWindow.xaml.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    //
    using System.IO;
    using System.Globalization;
    using System.Data;
    using System.Collections.ObjectModel;
    
    namespace _170611_t1030_readCsvFile
    {
        /// <summary>
        /// MainWindow.xaml の相互作用ロジック
        /// </summary>
        public partial class MainWindow : Window
        { 
            static readonly int kIndex_notSelected = -1;
            private int lastIndex = kIndex_notSelected; // DataGridの最後の選択
            private ObservableCollection<Person> myList;
    
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private void Window_Loaded(object sender, RoutedEventArgs e)
            {
                myList = new ObservableCollection<Person>();
                myList.Add(new Person { Name = "7of9", Race = "Borg", Codename = "seven" });
                myList.Add(new Person { Name = "Janeway", Race = "Human", Codename = "Captain" });
                myList.Add(new Person { Name = "Odo", Race = "Unknown", Codename = "Odo" });
                this.DataContext = myList;
            }
    
            private void B_delete_Click(object sender, RoutedEventArgs e)
            {
                if (lastIndex == kIndex_notSelected)
                {
                    return;
                }
                Person prsn = dg1.Items[lastIndex] as Person;
                myList.Remove(prsn);
    
                MessageBox.Show("deleted " + prsn.Name);
                lastIndex = kIndex_notSelected;
            }
    
            private void dg1_MouseLeave(object sender, MouseEventArgs e)
            {
                DataGrid dgc = sender as DataGrid;
                if (dgc == null)
                {
                    return;
                }
                lastIndex = dgc.SelectedIndex;
            }
        }
    
        // Name, Race, Codename
        public class Person
        {
            public string Name { get; set; }
            public string Race { get; set; }
            public string Codename { get; set; }
        }
    
    }
    

    MainWindow.xaml
    <Window x:Class="_170611_t1030_readCsvFile.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:_170611_t1030_readCsvFile"
            mc:Ignorable="d"
            Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
        <Window.Resources>
            <Style x:Key="keyCellStyle" TargetType="DataGridCell">
                <Style.Triggers>
                    <Trigger Property="TabIndex" Value="0">
                        <Setter Property="Background" Value="LightGreen"/>
                    </Trigger>
                    <Trigger Property="TabIndex" Value="1">
                        <Setter Property="Background" Value="LightGreen"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Window.Resources>
        <Grid>
            <StackPanel>
                <Button x:Name="B_delete" Content="delete"
                        Click="B_delete_Click" Width="100"/>
                <DataGrid Height="300" x:Name="dg1"
                          AutoGenerateColumns="True"
                          IsReadOnly="true"
                          CellStyle="{StaticResource keyCellStyle}"
                          ItemsSource="{Binding}" MouseLeave="dg1_MouseLeave"/>
            </StackPanel>
        </Grid>
    </Window>
    

    Odo를 선택.


    Delete 버튼을 누릅니다.
    Odo가 삭제됩니다.


    더 나은 UI



    왼쪽 열에 checkbox를 준비하고 선택한 행을 지웁니다.

    LINQ로 처리하게 될까.

    좋은 웹페이지 즐겨찾기