Insert and update in DLinq DataGridview

  • Thread starter Thread starter Andrus
  • Start date Start date
A

Andrus

I tried to edit data in DataGridView.
Insert and delete operations in grid are not saved to database. Updating
works OK.

How to force grid to save Insert and Delete operations also ?

Andrus.

Northwind db = CreateDB();
var list = new BindingList<Customer>(db.GetTable<Customer>().ToList() );
DataGridView grid = new DataGridView { Dock = DockStyle.Fill, DataSource =
list };
Form f = new Form { Controls = { grid } };
Application.Run(f);
db.SubmitChanges();
 
How to force grid to save Insert and Delete operations also ?
Insert may be easy to implement, you just need to attach new objects to
DataContext (with the Attach() method).
Delete is probably going to be a bit harder... :)

For insert/update I'm currently using the following code in save button:

void save_Click(object sender, System.EventArgs e) {
Grid.EndEdit();
if (!Validate())
return;
foreach (TRow row in Customers) {
if (!row.IsNew)
continue;
Grid.RowTable.Add(row);
}
int i = 1;
try {
DataBase.SubmitChanges();
} catch (Npgsql.NpgsqlException ex) {
MessageBox.Show("Cannot save");
return;
}
}


For delete I use in grid delete event:

if (row.IsNewRow)
return true;
BindingList<TEntity> bl = DataSource as BindingList<TEntity>;
RowTable.Remove(bl[row.Index]);
Rows.Remove(row);


Insert requires to implement IsNew property like

public abstract class EntityBase {
/// <summary>
/// True if row entity is new, not stored in db
/// </summary>
public bool IsNew {
get {
return (int)GetValue("Id") != 0;
}
}

I looked into MS samples. They assign bindinglist to bindingsource then
bindingsource to DataGridView DataSource. It seems that grid allows
automagically to insert and update data without writing such code.

So I'm interested which is the proper way.


Andrus.
 
Back
Top