Wednesday, March 25, 2009

Working with WPF DataGrid - Part 3

CRUD operations can be performed in WPF Datagrid using two approaches

1. By handling the Grid events

2. Handling the ObservableCollection events

In this article I will explain both the approaches which can be followed in a WPF application.

Handling Grid Events

WPF DataGrid,s BeginningEdit, RowEditEnding and the PreviewKeyDown events are useful for handling CRUD operations. By writing Event Handlers for these datagrid events you can track the changes in the data. In our example I have added the above mentioned events to the DataGrid like

<WPF:DataGrid Name="_employeeDataGrid"

BeginningEdit="OnBeginingEdit"

RowEditEnding="OnRowEditEnding"

PreviewKeyDown="OnKeyDown"

DockPanel.Dock="Top"

Grid.Row="1" Margin="12 0 12 0"

VerticalAlignment="Top"

ItemsSource="{Binding}" />

In the code behind file I have the code as

public partial class EmployeeView : Window

{

public BaseTranslator<Employee, UIEmployee> Translator { get; private set; }

bool m_IsEditMode;

public EmployeeView()

{

InitializeComponent();

Translator = new EmployeeTranslator();

}

private void OnBeginingEdit(object sender, Microsoft.Windows.Controls.DataGridBeginningEditEventArgs e)

{

m_IsEditMode = true;

}

private void OnRowEditEnding(object sender, Microsoft.Windows.Controls.DataGridRowEditEndingEventArgs e)

{

if (e.Row.DataContext is UIEmployee)

EmployeeFactory.Update(Translator.ViewToBusiness(e.Row.DataContext as UIEmployee));

}

private void OnKeyDown(object sender, KeyEventArgs e)

{

if (!m_IsEditMode)

{

if (e.Key == Key.Delete)

{

if (_employeeDataGrid.SelectedItem != null)

{

if (_employeeDataGrid.SelectedItem is UIEmployee)

EmployeeFactory.Remove(Translator.ViewToBusiness(_employeeDataGrid.SelectedItem as UIEmployee));

}

}

}

}

}

The EmployeeFactory is updated with the methods for Delete and Update

public static void Update(Employee employee)

{

Employee employeeToUpdate = EmployeeCollection.Find((x) => x.Id == employee.Id);

if (employeeToUpdate != null)

{

employeeToUpdate.FirstName = employee.FirstName;

employeeToUpdate.LastName = employee.LastName;

employeeToUpdate.Occupation = employee.Occupation;

employeeToUpdate.DateOfJoining = employee.DateOfJoining;

employeeToUpdate.IsContracter = employee.IsContracter;

}

else

{

m_Id += 1;

employee.Id = m_Id;

EmployeeCollection.Add(employee);

}

}

public static bool Remove(Employee employee)

{

return EmployeeCollection.Remove(employee);

}

The next part of the series I’ll show how to use the ObservableCollection events to handle CRUD operations on the DataGrid.

1 comment:

ojang said...

Please sent sample code to me
ahajob@gmail.com