tags:

views:

1177

answers:

2

I'm writing CRUD code for the WPF Datagrid.

In the TheDataGrid_CellEditEnding method below:

  • how do I get the original text before the user made the change?
  • I need the original text to be able to change the customer and save it back to the database with _db.SubmitChanges()

Here's the full solution with database if anyone wants to experiment with this:

http://www.tanguay.info/web/download/testDataGrid566northwindDatagrid.zip

XAML:

<toolkit:DataGrid x:Name="TheDataGrid" 
                  AutoGenerateColumns="True"
                  CellEditEnding="TheDataGrid_CellEditEnding"/>

code-behind:

private void TheDataGrid_CellEditEnding(object sender, Microsoft.Windows.Controls.DataGridCellEditEndingEventArgs e)
{
    //get the original text
    Customer customer = e.Row.Item as Customer;
    string customerID = customer.CustomerID;
    int displayIndex = (int)e.Column.DisplayIndex; // e.g. equals 4 when user edits the 5th column

    //HOW TO I GET THE ORIGINAL TEXT? THERE IS NO FIELDS METHOD IN THE LINQ-TO-SQL CLASSES
    string originalText = customer.Fields[displayIndex].value.ToString();

    //get the changed text
    TextBox changedTextBox = e.EditingElement as TextBox;
    string changedText = changedTextBox.Text;

    //inform user
    Message.Text = String.Format("cell was changed from {0} to {1}", originalText, changedText);

    //I NEED TO CHANGE THE CUSTOMER WITH THE ABOVE TEXT
    //BEFORE I SAVE IT BACK HERE
    _db.SubmitChanges();
}
+1  A: 

Why do you need the original text? Is it to display some informational message?

In your case, you seem to be binding the datagrid to your LinqToSQL objects. This means that the Customer object the row is bound to is already updated and all you need to do is call SubmitChanges().

Denis Troller
the Customer object in e.Rows.Item is not changed, the changed text is in e.EditingElement.Text, so I see my task here is pulling it out of the Textbox and putting it into the Customer, how can I get the e.Rows.Item customer to have the changes, that would be nice.
Edward Tanguay
I'm guessing that is because you are catching the event too early.Most people have a save button that carries out the work of calling SubmitChanges.Maybe if you work on the RowEditing events rather than the cell your changes would be reflected.
Denis Troller
Ok, that's what I did, but even when handline with RowEdting you quickly run into instances where you need to rollback the data: http://stackoverflow.com/questions/676783/how-to-rollback-changes-to-wpf-datagrid-control-using-linq-to-sql
Edward Tanguay
see my answer in that question.
Denis Troller
A: 

I found the samples in this blog very helpful http://blogsprajeesh.blogspot.com/2009/03/blog-post.html

It explains sorting using the collection and grid events.

Sujith Nambiar