CodeSniper
CodeSniper

Reputation: 493

Clear selected row data in wpf datagrid?

Hi everyone i am new to wpf and i got stuck at one point.I want to delete my datagrid row in wpf row by selecting that row .Till now i have searched a lot and written following code but all in vain. Code is:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        var g1 = dg;
        var g2 = dg;

        if (g1.SelectedIndex >= 0)
        {
            for (int i = 0; i <= g1.SelectedItems.Count; i++)
            {
                g2.Items.Remove(g1.SelectedItems[i]);
            }
        }
        g1 = g2;
    }

Any suggestion would be highly appreciable.

Upvotes: 1

Views: 2797

Answers (1)

Lee F
Lee F

Reputation: 569

I see that you're handling the button click event, presumably in the code behind of the window / control. This creates a strong coupling between the UI elements and the logic that sits behind, which in turn makes testing a lot harder.

I would consider using the MVVM pattern and doing this sort of thing in the View Model. Using this approach you can reduce the coupling between UI (View) and the logic (View Model).

I've put together a very simple application (targeting .Net 4.5) to demonstrate binding a collection to the data grid and how to delete the selected row.

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Width="525"
        Height="350">
    <Grid>
        <StackPanel>
            <DataGrid ItemsSource="{Binding People}" SelectedItem="{Binding SelectedItem}" />
            <Button Command="{Binding DeleteCommand}">Delete Selected Row</Button>
        </StackPanel>
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Windows;
using System.Windows.Input;

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

            DataContext = new MainViewModel();
        }
    }

Person.cs

using System;

namespace WpfApplication1
{
    public class Person
    {
        public string Forename { get; set; }

        public string Surname { get; set; }
    }
}

DelegateCommand.cs

using System;
using System.Windows;
using System.Windows.Input;

namespace WpfApplication1
{
    public class DelegateCommand : ICommand
    {
        private readonly Predicate<object> _canExecute;
        private readonly Action<object> _execute;

        public event EventHandler CanExecuteChanged;

        public DelegateCommand(Action<object> execute)
            : this(execute, null)
        {
        }

        public DelegateCommand(Action<object> execute,
                       Predicate<object> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)
            {
                return true;
            }
            return _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        public void RaiseCanExecuteChanged()
        {
            if (CanExecuteChanged != null)
            {
                CanExecuteChanged(this, EventArgs.Empty);
            }
        }
    }
}

MainViewModel.cs

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;

namespace WpfApplication1
{
    internal class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public MainViewModel()
        {
            People = new ObservableCollection<Person>();
            DeleteCommand = new DelegateCommand(x => DeleteSelectedItem(null));

            People.Add(new Person { Forename = "Bob", Surname = "Smith" });
            People.Add(new Person { Forename = "Alice", Surname = "Jones" });
        }

        private void DeleteSelectedItem(object obj)
        {
            People.Remove(SelectedItem);
            SelectedItem = null;
        }

        public ICommand DeleteCommand { get; set; }

        public ObservableCollection<Person> People { get; set; }

        private Person selectedItem;

        public Person SelectedItem
        {
            get { return selectedItem; }
            set
            {
                if (selectedItem == value)
                    return;

                selectedItem = value;
                OnPropertyChanged();
            }
        }

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Code behind

MainWindow.xaml.cs

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();

        DeleteCommand = new DelegateCommand(x => DeleteSelectedItem(null));
        People = new ObservableCollection<Person>();
        DataContext = this;

        Loaded += (sender, args) => PopulateCollection();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void PopulateCollection()
    {
        People.Add(new Person { Forename = "Bob", Surname = "Smith" });
        People.Add(new Person { Forename = "Alice", Surname = "Jones" });
    }

    private void DeleteSelectedItem(object obj)
    {
        People.Remove(SelectedItem);
        SelectedItem = null;
    }

    public ICommand DeleteCommand { get; set; }

    public ObservableCollection<Person> People { get; set; }

    private Person selectedItem;

    public Person SelectedItem
    {
        get { return selectedItem; }
        set
        {
            if (selectedItem == value)
                return;

            selectedItem = value;
            OnPropertyChanged();
        }
    }

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

Upvotes: 1

Related Questions