title: How to synchronize Database and DataGridView
body: <p>I have been trying to synchronize a database trough a <code>DataGridView</code>. So far I have created a data model class. This class contains multiple Properties that match the database. They are mapped using the <code>[Table]</code> and <code>[Column]</code> attributes from the <code>System.Data.Linq.Mapping</code> namespace.</p>
  
  <p>Ok. So I bound the <code>DataGridView</code> using the <code>DataSource</code>-Property to a <code>DataContext</code> connecting to the Database (MSSQL). This Logic is implemented in a <strong>singleton</strong> class, so I can assure there is a single instance of this <code>DataContext</code>.</p>
  
  <pre><code> this.m_context = new DataContext(conn);
   this.m_VisitorTable = m_context.GetTable&lt;Visitor&gt;();
  </code></pre>
  
  <p>Well, if I bind the table to my <code>DataGridView.DataSource</code> I can see all my entries from the database loaded and shown correctly. Then if I change something I found myself confronted with the synchronization problem. The changed cell did not change on the database side. </p>
  
  <p>To save the changes I implemented this method:</p>
  
  <pre><code>public void SaveChanges()
  {
      try
      {
         // I have no idea what I'm doing here.
         VisitorLogic.Instance.m_VisitorTable.Context.SubmitChanges(System.Data.Linq.ConflictMode.Con
         // I'm also trying to see if changes were made so I can save them before closing.
         this.m_bChangesMade = false;
      }
      catch (Exception ex)
      {
          MessageBox.Show("Failed to save.", "Error");
      }
   }
  </code></pre>
  
  <p>Is there a way to make the whole synchronizing to the database happen automatically? Like autocommit on change. I guess I will have to change something on the model Class. Right now, it does not implement any interfaces nor inherit anything.</p>
  
  <p>This is the class declaration:</p>
  
  <pre><code>[Table(Name = "tblVisitor")]
  public class Visitor
  </code></pre>
  
  <p>Further on, I have not found a way to update my <code>DataGridView</code> "correctly". This is how I make it now, but it seems it's not always working. Is there a better way to do this?</p>
  
  <pre><code>// Retrieve the new data from the database
  VisitorLogic.Instance.m_VisitorTable.Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, VisitorLogic.Instance.m_VisitorTable);
  
  
  // Set the DataSource to 'null'
  this.dataGridView.DataSource = null;
  
  // Refresh (?!)
  this.dataGridView.Refresh();
  
  // Bind the new DataSource, hoping it will show the new data.
  this.dataGridView.DataSource = VisitorLogic.Instance.m_VisitorTable;
  this.m_bChangesMade = false;
  </code></pre>
  
  <p>Thanks for your help!</p>