I have been trying to synchronize a database trough a DataGridView
. So far I have created a data model class. This class contains multiple Properties that match the database. They are mapped using the [Table]
and [Column]
attributes from the System.Data.Linq.Mapping
namespace.
Ok. So I bound the DataGridView
using the DataSource
-Property to a DataContext
connecting to the Database (MSSQL). This Logic is implemented in a singleton class, so I can assure there is a single instance of this DataContext
.
this.m_context = new DataContext(conn);
this.m_VisitorTable = m_context.GetTable<Visitor>();
Well, if I bind the table to my DataGridView.DataSource
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.
To save the changes I implemented this method:
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");
}
}
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.
This is the class declaration:
[Table(Name = "tblVisitor")]
public class Visitor
Further on, I have not found a way to update my DataGridView
"correctly". This is how I make it now, but it seems it's not always working. Is there a better way to do this?
// 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;
Thanks for your help!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…