WPF: Adding and deleting items in DataGrid

This entry is part 38 of 54 in the series Learn WPF

I have taken the example from this post from MSDN on adding, deleting, updating information in DataGrid.

In this example, we create an ObservableCollection class as data source, which implements INotifyPropertyChanged,  set  a collection of class Customers as its children.

Next, we bind the data source to the DataGrid.

MainWindow.xaml
<Window x:Class="DataGridName.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="350" Width="300"
    xmlns:local="clr-namespace:DataGridName"
        >
    <StackPanel>
        <DataGrid AutoGenerateColumns="True" Name="datagrid"  />
        <GroupBox Header="Add Data">
            <!--add data-->
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <TextBlock Text="ID" Grid.Row="0" Grid.Column="0" />
                <TextBlock Text="Name" Grid.Row="0" Grid.Column="1" />
                <TextBlock Text="SecNumber" Grid.Row="0" Grid.Column="2" />
                <TextBox Name="txtID" Grid.Row="1" Grid.Column="0" />
                <TextBox Name="txtName" Grid.Row="1" Grid.Column="1" />
                <TextBox Name="txtSecNumber" Grid.Row="1" Grid.Column="2" />
            </Grid>
        </GroupBox>
        <!--show the selected item-->
        <GroupBox Header="Show Selected Item">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <TextBlock Text="ID" Grid.Row="0" Grid.Column="0" />
                <TextBlock Text="Name" Grid.Row="0" Grid.Column="1" />
                <TextBlock Text="SecNumber" Grid.Row="0" Grid.Column="2" />
                <TextBox Name="txtShowID"  Grid.Row="1" Grid.Column="0" Text="{Binding ElementName=datagrid,Path=SelectedItem.ID}" />
                <TextBox  Name="txtShowName" Grid.Row="1" Grid.Column="1" Text="{Binding ElementName=datagrid,Path=SelectedItem.Name}" />
                <TextBox  Name="txtShowSecNumber" Grid.Row="1" Grid.Column="2" Text="{Binding ElementName=datagrid,Path=SelectedItem.SecNumber}" />
            </Grid>
        </GroupBox>
        <StackPanel Orientation="Horizontal" >
            <Button  Content="Add"  Click="btnAdd" Width="50" Height="30" />
            <Button  Content="Update"  Click="btnUpdate" Width="50" Height="30" />
            <Button  Content="Delete"  Click="btnDelete" Width="50" Height="30" />
        </StackPanel>
    </StackPanel>
</Window>

Notice in this example, I have used GroupBox and combine it with Grid to form the Add Data and Show Selected Item group.


MainWindow.xaml.cs
using System.Collections.ObjectModel;
using System.Windows;
namespace DataGridName
{
    public class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string SecNumber { get; set; }
    }

    public partial class MainWindow : Window
    {
        ObservableCollection<Customer> col;

        public MainWindow()
        {
            InitializeComponent();
            col = new ObservableCollection<Customer>();
            col.Add(new Customer() { ID = 1, Name = "John", SecNumber = "A498" });
            col.Add(new Customer() { ID = 2, Name = "Michelle", SecNumber = "B812" });
            col.Add(new Customer() { ID = 3, Name = "Emily", SecNumber = "B871" });
            col.Add(new Customer() { ID = 4, Name = "David", SecNumber = "D455" });
            datagrid.ItemsSource = col;
        }

        private void btnAdd(object sender, RoutedEventArgs e)
        {
            int id = 0;
            try
            {
                id = int.Parse(txtID.Text.Trim());
                col.Add(new Customer() { ID = id, Name = txtName.Text.Trim(), SecNumber = txtSecNumber.Text.Trim() });
            }
            catch
            {
                MessageBox.Show("ID must be int type");
            }
        }

        private void btnDelete(object sender, RoutedEventArgs e)
        {
            if (datagrid.SelectedIndex >= 0)
            {
                //remove the selectedItem from the collection source
                Customer customer = datagrid.SelectedItem as Customer;
                col.Remove(customer);
            }
        }

        private void btnUpdate(object sender, RoutedEventArgs e)
        {
            if (datagrid.SelectedIndex >= 0)
            {
                // get the selected's infomation first
                Customer newCustomer = new Customer();
                newCustomer.ID = int.Parse(txtShowID.Text);
                newCustomer.Name = txtShowName.Text.Trim();
                newCustomer.SecNumber = txtShowSecNumber.Text.Trim();

                // remove the old information
                Customer customer = datagrid.SelectedItem as Customer;
                col.Remove(customer);

                //add a new customer
                col.Add(newCustomer);
            }
            else { MessageBox.Show("Please Select And Update An Item."); }
        }
    }
}

datagrid

Series Navigation<< WPF: Populating a datagrid using a collection
WPF: Binding to a collection >>
Posted in

Leave a comment

Leave a Reply