Donate

WPF Add Or Delete Rows In A DataGrid Using Observable Collection

Here's a simple way of adding/deleting WPF Datagrid rows using observable collection.
XAML Code
1
2
3
4
5
6
7
8
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding}" Margin="12,12,12,41" Name="dataGrid1" CanUserResizeRows="False" CommandManager.PreviewExecuted="UserDataGrid_PreviewDeleteCommandHandler" RowEditEnding="dataGrid1_RowEditEnding" RowHeaderWidth="20">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding UserName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="User name" Width="230">
        </DataGridTextColumn>
        <DataGridTextColumn Binding="{Binding FirstName,  Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Header="First Name" Width="245">
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

C# Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public partial class MainWindow : Window
    {
        private ObservableCollection<User> users = new ObservableCollection<User>();
        private StringBuilder builder;
 
        public ObservableCollection<User> AllUsers
        {
            get { return users; }
            set { users = value; }
        }
 
        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        { }
 
        public MainWindow()
        {
            InitializeComponent();
            users.Add(new User() { UserName = "Walter", FirstName = "Walter North" });
            dataGrid1.ItemsSource = AllUsers;
            AllUsers.CollectionChanged += AllUsers_CollectionChanged;
        }
 
        private void dataGrid1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            // Get Items From Source
            builder = new StringBuilder();
            if (e.EditAction == DataGridEditAction.Commit)
            {
                foreach (object item in AllUsers)
                {
                    if (item.GetType().Equals(typeof(User)))
                        builder.AppendLine(String.Format("{0},{1}", ((User)item).UserName, ((User)item).FirstName));
                }
 
                MessageBox.Show(String.Format("{0}",builder.ToString()), "Items in collection!");
            }
        }
 
        private void UserDataGrid_PreviewDeleteCommandHandler(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Command == DataGrid.DeleteCommand)
            {
                if (!(MessageBox.Show(String.Format("Delete Current Item {0} ?", ((User)((DataGrid)sender).CurrentItem).UserName), 
                    "Please confirm.", MessageBoxButton.YesNo) == MessageBoxResult.Yes))
                {
                    e.Handled = true; // Cancel Delete.
                }
            }
        }
 
        private void AllUsers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            // If action is remove, show current collection
            if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                builder = new StringBuilder();
                foreach (var item in AllUsers)
                {
                    builder.AppendLine(String.Format("{0},{1}", ((User)item).UserName, ((User)item).FirstName));
                }
 
                MessageBox.Show(String.Format("{0}", builder.ToString()), "Items in collection!");               
            }
        }
    }

Screenshot
WPF Add Or Delete Rows In A DataGrid Using Observable Collection

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.