Add/ Delete programmatically.

Sep 8, 2009 at 3:34 AM

Can someone please tell me how to successfully add and delete rows manunally in C#?

I am using the WPF Datagrid, and LINQ to SQL.  When I endable CanUserAddRows and CanUserDeleteRows it works ok (most of the time, although sometimes I get Null references because I have a composite key but that is another topic).

But I cannot get it to delete manually.  Is there a way to call the same internal commands that the datagrid uses to add and remove entities?


I am trying something like the following..

private void AddCommand_Executed(object sender, ExecutedRoutedEventArgs e)
            item item = new item();
            item.SetDefaults(invoice, db);


            DataGrid.ItemsSource = invoice.items.GetNewBindingList();


private void DeleteCommand_Executed(object sender, ExecutedRoutedEventArgs e)
            item item = DataGrid.SelectedItem as item;

            if (item!= null)

                 if (item.citemid != 0)

                DataGrid.ItemsSource = reptran.repitems.GetNewBindingList();



Detach, is a method which sets all entity references to null.  Without this method the item still has references to other entities such as TAX rate.

The problem that I am getting is that despite setting all references to null, SaveChanges works when the entity exists, but if I add an item, and remove it before saving SaveChanges() still tries to insert it in the database.   this fails because of my composite key, but I also dont want it because it would be an orphaned record in the database.

What is wrong here?