Reputation: 3
I've been looking around a lot and I cannot figure out where this problem is coming from. What's happening is that I have a datagridview using a BindingSource, SqlDataAdapter, SqlCommandBuilder, and a DataTable. The datagridview is populated with a simple select query (which only uses one table from the MSSQL Server DB). I want to be able to edit things in this table. Right now, editing works, but not the way it should. I would think that I would be able to edit a cell, hit enter, and have the changes committed to the database. What actually happens, is that the changes do not appear until I finish editing a second cell. Anyone know what I'm overlooking here? Thanks!
Here is the relevant code in the .cs file:
public partial class CheckIn : Form
{
private BindingSource searchDGVBindingSource = new BindingSource();
private SqlDataAdapter searchDGVDataAdapter;
private SqlCommandBuilder searchDGVSqlCommandBuilder;
private DataTable searchDGVDataTable;
public CheckIn()
{
InitializeComponent();
this.Load += new System.EventHandler(CheckIn_Load);
}
private void CheckIn_Load(object sender, EventArgs e)
{
searchDGV.DataSource = searchDGVBindingSource;
searchDGVDataAdapter = new SqlDataAdapter(selectCommand, connectionString);
searchDGVSqlCommandBuilder = new SqlCommandBuilder(searchDGVDataAdapter);
searchDGVDataTable = new DataTable();
searchDGVDataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;
searchDGVDataAdapter.Fill(searchDGVDataTable);
searchDGVBindingSource.DataSource = searchDGVDataTable;
searchDGV.AutoResizeColumns();
}
private void searchGridView_RowEndEdit(object sender, DataGridViewCellEventArgs e)
{
searchDGVDataAdapter.Update(searchDGVDataTable);
}
}
Here is the relevant code from the .Designer.cs file:
//
// searchDGV
//
this.searchDGV.AllowUserToAddRows = false;
this.searchDGV.AllowUserToDeleteRows = false;
this.searchDGV.BackgroundColor = System.Drawing.Color.White;
this.searchDGV.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.searchDGV.Location = new System.Drawing.Point(10, 250);
this.searchDGV.MultiSelect = false;
this.searchDGV.Name = "searchDGV";
this.searchDGV.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.searchDGV.Size = new System.Drawing.Size(619, 150);
this.searchDGV.TabIndex = 7;
this.searchDGV.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.searchGridView_CellClick);
this.searchDGV.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.searchGridView_RowEndEdit);
Upvotes: 0
Views: 2898
Reputation: 7961
You need to call searchDGVBindingSource.EndEdit()
in your event handler and it will work:
private void searchGridView_RowEndEdit(object sender, DataGridViewCellEventArgs e)
{
searchDGVBindingSource.EndEdit();
searchDGVDataAdapter.Update(searchDGVDataTable);
}
Check documentation for BindingSource.EndEdit()
to learn more about it.
Upvotes: 2