Insert and update in DLinq DataGridview

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();
 
A

Andrus

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top