Home » WPF

WPF DataGrid C# LINQ SubmitChanges()


I have a table stored in an SQL database that I wish to display in a WPF DataGrid using LINQ. Some cells are displayed as they appear in the database while other cells are the results of computations I make on data from the SQL database. Then I wish to edit some cells which must be updated in the SQL database and after such an edit the entire DataGrid must be updated because some of the cells need to be re-computed based on what I just entered.

Let me demonstrate with a brief example. I have the following XAML code:

<DataGridx:Name="Holdings"AutoGenerateColumns="False"><DataGrid.Columns><DataGridTextColumnHeader="Name"Binding="{Binding Name}"IsReadOnly="True"/><DataGridTextColumnHeader="Count"Binding="{Binding Count, Mode=TwoWay}"IsReadOnly="False"/><DataGridTextColumnHeader="Result"Binding="{Binding Result}"IsReadOnly="True"/></DataGrid.Columns></DataGrid>

Here the Name and Count columns are taken directly from the database and I wish to edit the Count, and then Result must be re-computed for all rows.

In the code-behind I have:

publicpartialclass HoldingsList : UserControl
  public HoldingsList()

    // New connection to SQL database.
    MyDB db = new MyDB();

    // Display table from database in DataGrid.
    Holdings.ItemsSource = db.Holdings;

And I have extended the Holding-class (which is generated by the SQL-to-LINQ tool where I drag and drop the SQL tables and it creates the code-behind automatically) so as to compute the Result-value using the Count-values for all entries in the database (actual calculation omitted here):

publicpartialclass Holding
  publicdouble Result
      // Make calculation using the Count-value for all database-entries. (Omitted.)return 12.34;

I have two problems:

(1) I cannot get the edited Count-value to actually get updated in the SQL database. It seems I need a db.SubmitChanges() but I can't find out where to place this, I've tried implementing CellEditEnding and RowEditEnding but these are called before any data in the database has actually been changed. I've also tried implementing CurrentCellChanged which seemed to work but it is not the proper use of this event as it is used for changing cells in general. So where should I call db.SubmitChanges()? Or is there a way to set up the XAML code so that it automatically calls db.SubmitChanges()?

(2) How do I get the entire DataGrid to refresh / recalculate all of its values? I've tried creating a new MyDB and assign it to Holdings.ItemsSource but combined with the problem I describe in (1) it doesn't seemto work. I have also tried calling InvalidateVisual which doesn't work either. The important thing to note is that some of the data is displayed directly from the database while the Result-column is computed.

Thanks in advance!



5 Answers Found


Answer 1

Hi CoderMP,

You created a custom class  to wrap the data  from the database, so I have one question, do you implement the INotifyPropertyChanged interface? If yes, then we can discuss the next question.

For the (1) question: You could set  the Binding.NotifyOnTargetUpdated property and the Binding.NotifyOnSourceUpdated property to ture, that you could add the event  handler of the SourceUpdated and the TargetUpdated. The SourceUpdated event will be fired after the Binding Source is updated. So you could update the datat into database  in this event handler. Please refer to this document: http://msdn.microsoft.com/en-us/library/system.windows.data.binding.sourceupdated.aspx

For the (2): It is unnecessary to call  the InvalidateVisual or UpdateLayout, they are used to update the visual element of the DataGrid, not the data. If you have implemented the INotifyPropertyChanged interface, any changes in the Source can be notified to the element and the DataBinding can update the element automatically.

Hope this helps.


Bob Bao


Answer 2

Hi Bob Bao,

Thanks. It's not really a wrapper-class I've made I've just extended  the Holding-class that was automatically generated  from the SQL database  (note the 'partial' keyword) and which already implements INotifyPropertyChanged, so I guess I don't have to?

I've solved my problems  but I'm not sure it is the correct / intended way. What I've done is added the following to the Holdings-class:

// The database connection  remains open.
MyDB db = new MyDB();

// We are not allowed to call  Refresh() inside CellEditEnding so we need a hack.bool justSaved = false;

privatevoid Holdings_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
  if (e.EditAction == DataGridEditAction.Commit)

    justSaved = true;

privatevoid Holdings_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
  if (justSaved)

    justSaved = false;

 And then in the WPF I've added event-handlers to these and I've added the statement UpdateSourceTrigger=PropertyChanged to the binding. This seems to work. Is it a proper  way of doing this or have I opened the door for a swarm of bugs? Please provide source-code if you have a solution that is better than mine, it will be helpful for future readers as well.



Answer 3


I think I have a better way for you to solve this problem... the intended way, so to speak.  I encountered the same issue.  I'm not going to include source code, however, because it is all tangled with stuff that would only obfuscate the simplicity of the solution:

When you set  the datasource for your datagrid  you will want to subscribe to the PropertyChanged events of each item in the grid.  In that event  handler method you can then submit your changes to the database.  You just want to be careful to unsubscribe to these events when you change your datasource, otherwise the objects will never get garbage collected.




Answer 4

Hi CoderMP,

As Psychlotron said, handle the event  will not bring the bugs. The following article introduces the usage of the DataGrid in WPF in details, you may need it: http://www.codeproject.com/KB/WPF/WPFDataGridExamples.aspx#dataset


Bob Bao


Answer 5

Thanks for the replies, but without source-code I'm afraid I don't understand what must be done. I've also looked at the page linked to by Bob Bao but I'm not sure the solution provided there is simpler or better than mine(?)

When working with WPF it keeps occurring to me that WPF is much more complicated than C# itself. Hopefully the Microsoft developers will prioritize the streamlining of WPF in the future? Also, the MSDN pages on WPF could be improved significantly. If you note  the number of views this forum-thread has had in such a short period of time it would seem that many people are confused by WPF.



I'm using Linq to Entities and bind a linq query to the WPF 4 DataGrid datacontext.  The linq query look something like this:     

            var query = from s in this.db.Customers
                        orderby s.Name
                        select s;

            private ContextEntities db = new ContextEntities();
            private BindingListCollectionView View;

            this.View = ((BindingListCollectionView)CollectionViewSource.GetDefaultView(query));
            this.DataContext = this.View;

If my Customers table does not have any record, the DataGrid does not show any row for user to add.  I have CanUserAddRows set to true.  I found another post that address this issue but it say to create a new entity type.  http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/cdc0fb6f-2335-42e2-98d7-4bd73ffffc8c

My project currently bind to the View/query, how can I create new entity type?  Can someone offer a solution?



When I create the DataContext and call the submitChanges within the same control, it works.
But if I pass in the DataContext into the control.


        public Patient(Huijing_Project.Models.HuijingDataContext dc)



            var list = from p in dc.GetTable<Huijing_Project.Models.Patient>()

                       select p;

            dataLayoutControl1.DataSource = list;


after that I modify the data in the customControl and then call the dataContext.submitChanges outside the control

dc.submitChanges(). It won't work, If I modified 10 fields, most of the time it only update 8/9 of 10. What's up ?
I am sure no matter which means, I am sure that I load data or submitChanges with same dataContext.



I am getting an error when I try to call the SubmitChanges() on a DataContext.

I update 1 field in an item from a list, but when I call submitchanges I get the following error:

"Incompatible column types. Previous type: Invalid . Current type: Lookup"

in: Microsoft.SharePoint.Linq.EntityTracker.ValidateMapping()

I looked at the list item and the value I am updating it with and they are both the same.

Also, I can not debug submitchanges() it will not let me step through it. Also, how come I can't find "Microsoft.SharePoint.Linq.EntityTracker.ValidateMapping"  anywhere on MSDN or google??




I've been using LINQ for a few years but just now using the Code Analysis feature of VS.NET2010.  I'm getting a lot of warnings in funtions I have that use the LINQ SubmitChanges() method yet I am unable to determine what change(s) I need to make to satisfy code analysis.  The CA2000 warning is the  one related to needing to dispose object ...


I've isolated the one statement that calls SubmitChanges as being the culprit.  If I comment the line the warning disappears.  What am I missing?  My goal is to change my code so there are no CA warnings ...

PublicSub DeleteOpenLock(ByVal BuildConfigurationName AsString, ByVal userName AsString, ByVal fqn AsString)

    Using context = New BuildWizardDbDataContext(dbConnectionString)

      Dim lock = (From x In context.BuildConfigurationLocks
             Where BuildConfigurationName = x.BuildConfiguration.Name _
             AndAlso x.BuildSystem.Fqn.ToLower = fqn.ToLower AndAlso _
             x.UserName.ToLower = userName.ToLower
             Select x).SingleOrDefault

      IfNot lock IsNothingThen


I have an XML string in memory, which I want to write to my database. I'm using LINQ

But SubmitChanges() isn't working. Everything works fine up to that point, and all the values are correct when I debug. The database values just aren't updated.


//pare down xml to contain locations only
        //using LINQ
        XElement resultData = XElement.Parse(xmlResult);  //xmlResult is the string containing the XML
        var locationsXmlData = from lc in resultData.Descendants("location")
                        select lc;

        //for each location, write data to database
        LocationDataContext locationData = new LocationDataContext();

        foreach (var locationXmlElement in locationsXmlData)  
            XElement xmlId = locationXmlElement.Element("locationid");
            //check if id/key already exists for this location
            var queryExists = from dbRow in locationData.locations  //locations is db table name
                              where dbRow.locationid == (string)xmlId
                              select new { dbRow.locationid };

            if (queryExists.Count() == 1)  //row exists, do database UPDATE
                var locx = locationData.locations.Single(x => x.locationid == (string)locationXmlElement.Element("locationid"));

                string debug = (string)locationXmlElement.Element("name");
                //locx.name = (string)locationXmlElement.Element("name");
                locx.name = debug;

                locationData.SubmitChanges();  //DOESN'T WORK, DATABASE TABLE NOT UPDATED
            else  //row doesn't exist, do database INSERT


I was trying to delete records from database and sometimes on production, the SubmitChanges() goes through and updates the associated entities yet the data does not gets deleted in the database. This is happening only in production and I could not replicate the same on stage or on my local machine. Now the table in which I am performing the delete transaction does have primary keys.

Any suggestions ??


I was trying to delete records from database and sometimes on production, the SubmitChanges() goes through and updates the associated entities yet the data does not gets deleted in the database. This is happening only in production and I could not replicate the same on stage or on my local machine. Now the table in which I am performing the delete transaction does have primary keys.


Any suggestions ??



Many of you might have noticed that the WPF DataGrid looks very blah compared to the Silverlight DataGrid.

Here are the WPF DataGrid Screenshot and Silverlight DataGrid Screenshot.

See how in the Silverlight DataGrid the lines are better, there are alternating row backgrounds and the selected row also looks better.

I am surprised the WPF DataGrid doesn't use the same styles by default as the Silverlight.

Has anyone styles the WPF DataGrid to make it look like the Silverlight DataGrid and if so can you share the templates with me?

Or is there a built-in theme in WPF DataGrid that looks close to the Silverlight DataGrid?



I need to have a column header on 2 lines in the WPF DataGrid...
How can I do that?


I m using linq to entities, windows forms. i did more development on Web.

How do i wrap the linq to entities to a grid view . I have like first name, lastname, phone numbers from a person object

i want to display list of persons in  datagrid but phone numbers needs to be combo box. Phone numbers are from different table. 

I get a list of anonymous object with firstname, last name and phone numbers ? how can i display in datagrid and do crud operations.



I have a SQL table with the following fields

ID ( key)



I would like to make a datagrid with a itemsource based on a LINQ Query for obtaining the SUM of the profit per year and to get the numbers ID with a  negative profit.

For the sum I managed to make something with the following code : 

    Dim lijst = From x In testlijst
                    Order By x.Year Descending
                    Group By x.Year Into SomProfit = Sum(x.Profit),
                    Select New SummeryReturn With {.Year = Year, .Profit = SomProfit }


But how should I write to code to obtain the numbers of ID with a negative Profit in the same LINQ query as the one above.

So I can make a datagrid with 3 fields ( class SummeryReturn) Year , SumProfit , NumberNegativeReturn.

Kind regards,




I surfed lot of articles in the net and finally  I am posting this thread.


I have designed a WCF Service with Oracle Database  without entity frame work.


I successfully got data from database to DataGrid in silverlight3.


This DataGrid has 5 columns out of which  2 columns user can do updates directly in Datagrid.


After he clicked on the Submit button, these user changes along with other read only column details have to insert/update in database.


I have written Update query in WCF but my main issue is how to get all rows and columns values along with change details from Datagrid to send WCF service.


Please help me if you have any idea.


It will be great if you provide code sample


I am attempting to bind XML data to a silverlight DataGrid via Linq.  Included in that data is a column of dates (birth dates) that may be empty.  My data item structure uses a nullable DateTime object to store the birthdate.  The birthdate in the XML is either '.' if the date is unknown, or in the format 02MAR71.  I have the basic binding working as desired (data is loaded into the grid), but some of the refinements that I'd like to add are giving me trouble...

I have several issues that I am struggling to solve:

1.  How to I set a format on the birthdate column to something that doesn't include the time?  I considered creating my own time (Date) and providing an override for ToString() that provides the string in the proper format.  If I do that, I also have to write code to provide sorting.  If I can stay with a DateTime object and simply set a format, the sorting just works.

2.  How do I add a grouping clause?  I'd like to be able to Company or Region or whatever, based on a user preference.

3.  How do I provide a custom sort order for the Rank column?  Since the DataGrid considers that column strings, the sort results in alphabetical order.  I really want them to be listed according to rank order.

4. Eventually, I plan on adding custom column ordering.  I plan on displaying the DataGrid the very first time with a default set of columns in a predetermined order, but provide the ability for the user to reorder and hide/show different columns.  Once the user has things the way they want, I want to allow them to save that layout such that the next time the DataGrid initializes with the right columns ordered as they wanted.  Is Linq going to provide enough flexibility to allow this type of functionality or amy I just going to have to load all columns in the default order and then reorder and hide/unhide the columns as needed?  (If that's the way to go, I shouldn't have trouble doing that as a second phase of InitializeGrid.)

Here's the current code:

publicvoid InitializeGrid()
  XDocument xdoc = XDocument.Load( "SampleData.xml" );
  var myData = from info in xdoc.Descendants( "People" )

  selectnew Person
   Name = info.Attribute( "name" ).Value,
   Company = info.Attribute( "company" ).Value,
   Birthdate = ParseDate( info.Attribute( "birthdate" ).Value,
   Rank = info.Attribute( "rank" ).Value,
   Region = info.Attribute( "region" ).Value
  dataGrid.ItemsSource = myData;

private DateTime? ParseDate( string pre )
  if ( pre.Equals( "." ) )
  elsereturn DateTime.ParseExact( pre, "ddMMMyy", CultureInfo.InvariantCulture );


I'm trying to fill a DataGrid with the TimeZones using Linq so I can query them.

I've filled a ComboBox on a web page with the data I need (Code Below)

But I want a WindowsForm with the same data but would like to use a SELECT statement to query this.



Dim tzi AsReadOnlyCollection(OfTimeZoneInfo)

tzi =





ForEach TimeZone AsTimeZoneInfoIn tzi



NewListItem(TimeZone.DisplayName, TimeZone.Id))



Next TimeZone

Hope this makes sense.



I have a DataGrid that's bound to an observable collection.

The grid has a column defined as follows:




DataGridTextColumn Header="Quantity" Binding="{Binding quantity, NotifyOnValidationError=True}"></DataGridTextColumn>

 quantity is a decimal.


So, if I enter a bogus value in the column (e.g. 1.04asdf), I get a validation error.

If I subsequently delete the item from the observable collection that has the error while the error exists, I can no longer edit any other columns in the DataGrid.

Is there a workaround for this?



I have a shiny new wpf 4 datagrid, and no matter what I do I can't make the row highlight when the user clicks on a cell. It works on the empty "new record" row on the bottom, but not on rows with data (yes I've tried with and without readonly).

My XAML is:

        <DataGridAutoGenerateColumns="False"Background="Beige"  Height="353"SelectionUnit="FullRow"SelectionMode="Single"AlternatingRowBackground="lightcyan"  HorizontalAlignment="Left"Name="dgJobs"VerticalAlignment="Top"Width="1160">
<DataGridTextColumnHeader="Job ID"Width="80"Binding="{Binding JobID}"IsReadOnly="True"></DataGridTextColumn>
<DataGridTextColumnHeader="Site"Width="SizeToCells"Binding="{Binding AssetName}"IsReadOnly="True"></DataGridTextColumn>
<DataGridTextColumnHeader="Category"Width="SizeToCells"Binding="{Binding CategoryName}"IsReadOnly="True"></DataGridTextColumn>
<DataGridTextColumnHeader="Status"Width="SizeToCells"Binding="{Binding JobStatusDesc}"IsReadOnly="True"></DataGridTextColumn>
<DataGridTextColumnHeader="Reason"Width="SizeToCells"Binding="{Binding Reason}"IsReadOnly="True"></DataGridTextColumn>

Nothing too fancy, it's quite plain really. I had themes enabled because I'm using a Fluent Ribbon elsewhere and it forces you to, but I tried turning that off and it had no effect.

The datasource is a list of subsonic activerecord items, if that's relevant.

I have a 3.5 form in another app which is also very plain and you can highlight the row on it. Why on earth isn't this one working?


EDIT: In related news, SelectedItem isn't changing when you click on different rows (it stays at the first record you select) and SelectedIndex is always -1.

It happens whenever the ItemsSource is something other than a datatable (which seems to work).

A List, an IList, ObserveableCollection, an IQueryable... they all kill record selection and highlighting. What the...?


Hi All,

I Have a Button to Add Datagrid Dynamically ,It can add any number of Datagrid controls

But i dont no how to add columns to those Datagrids....

Any Help????


Thanks in Advance.



Hi list,

does any body know what control I need in wpf to work with datagrid view (sql server handelling data)? Also How can I use it in wpf to pull data from sql server?




i dont see the wpf datagrid control in my toolbox. is this the result of an incorrect install or do i need to add a reference to a dll?

Hi All,

I'm new to WPF development.  I have designed an application in WPF that scans table every 35 seconds and displays all records in a WPF Toolkit DataGrid control.    This application runs as a management console type and it scans table every 35 seconds 24 hours.   Apparently I noticed there a hughe memory leak.  In few days it goes upto easily 1.5 gb of memory.  Although I'm only displaying 600 rows x 7 columns in every scan.   The scan on the table that happens every 35 seconds is relatively same.    Through my investigation and running through ANTS profiling I came to know that:

a) System.Collections.Generic --Dictionary<Tkey,TValue>+Entry<DependencyProperty,bool[]> has live instances over 50,000 and it keep increasing.   After a bit looking into the profiler it appears that there are chain references and because of that it is not garbage collected.  The chain reference is from DataGridHelper._propertyTransferEnablemap --> Microsoft.Windows.Controls.Weakhasttable---> System.collections.Hastable + bucket[] --> system.Collections.GenericDictionary<windows.DependencyProperty, bool>

I don't understand what is the exact chain and how do I break the chain reference.   Here is what I do in code to bind the Observable Collection to DataGrid.DataContext

In nutshell

Private void PopulateGrid()   //this function is called every 35 seconds



jobs = new JobService();   //Jobs object basically has Observable collectin property called JobList.  This class basically connects to //Database and builds the collection of data retrieved

this.DataGrid.dataContext = Jobs


Private Void CleanGridView()


 if(jobs!=null){ Jobs.dispose(); Jobs = null}  //release manged code


Plz help here as my knowledge to WPG is relative very weak and I need to deploy this application in production where it will be running 365 days.  

Also I can send you the whole project to see in details but I don't know if I can attach a project here.

thanks in advance.





<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure