问题
I have a DataGridView populated with a DataSet from my Database. I am trying to make changes in the DataGridView and apply those changes to the Database whenever I press 'Enter'.
Iv read alot of this same question, and researched the topic, but am still having trouble figuring out why I cannot apply changes made in my DataGridView to my Database. (I know this has been asked before, but still cant figure this out).
Can anyone show me what im doing wrong?
DataSet ds = new DataSet();
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlDataAdapter da;
public ListForm()
{
//Setting up DataGridView with data.
InitializeComponent();
da = new SqlDataAdapter("Select * from Contact_List", constring);
SqlCommandBuilder cmb = new SqlCommandBuilder(da);
da.UpdateCommand = cmb.GetUpdateCommand();
da.Fill(ds, "Contact_List");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Contact_List";
}
//Trying to update database with DataAdapter
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
//I believe that the changes to the database should be applied here
//Buts its not working
da.Update(ds, "Contact_List",);
ds.AcceptChanges();
con.Close();
}
}
回答1:
You should end current edit before trying to save changes:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var cm = dataGridView1.BindingContext[ds, "Contact_List"];
cm.EndCurrentEdit();
da.Update(ds, "Contact_List");
}
Some other notes
- You don't need a
DataSet. ADataTableis enough. - When you create a
SqlCommandBuilderby passing aSqlDataAdapterto the constructor, all insert, update and delete commands will be generated automatically and you don;t need to do anything yourself, soGetUpdateCommand()is not necessary. - Calling EndCurrentEdit cause the changes which you made on an IEditableObject be saved to underlying data source.
DataRowViewwhich is the object behind rows of grid is anIEditableObjectand you should callEndCurrentEditof the currency manager which causeEndEditofDataRowViewbe called and commits changes to the underlyingDataRowand ends the editing session. - If you bind the grid to a
BindingSource, callingEndEditofBindingSourcewill do the same. - After saving data, you don't need to call
AcceptChangesmanually. - You need to add exception handling to code.
回答2:
it's because you're using SqlCommandBuilder, I haven't used it in a long time and I'm looking for more info, but I believe you can only update one table, no joins, and there has to be a unique key defined, otherwise you may want to generate your UPDATE statement manually.
reference
来源:https://stackoverflow.com/questions/38797195/why-wont-datagridview-update-database