views:

83

answers:

2

Hello,

I'm using databinding (through LINQ to SQL) in a C# form and I need to know how to update the BindingContext when a new item is added to my Table.

More specifically, I have form that displays the properties of a project in various fields. The user can traverse to different projects through the project name combo box. At the bottom of the form I have a create button and a delete button. The problem arrises when the user creates or deletes a project because the binding context is not updated with the new list of projects. Therefore the user can not traverse to the new project or worse yet, the user can traverse to and attempt to modify a project that has been deleted.

I wish that I could call some method after a create or a delete so that the binding would update. Something like this.BindingContext[db.Projects].UpdateDammit().

Thanks for your help, JB

A: 

Make sure whatever you bind to can notify UI that the changes were done. If your binding context is a collection you can use ObservableCollection

If you bind to particular elements of the collection you need to make sure elements implement INotifyPropertyChanged and you raise notification when a value changes.

Vitalik
Unfortunately I'm using `System.Data.Linq.Table` and I can't really subclass it.`public sealed class Table<TEntity> : IQueryProvider, ITable,` `IListSource, ITable<TEntity>, IQueryable<TEntity>,` `IEnumerable<TEntity>, IQueryable, IEnumerable`
John Berryman
I assume you make changes to the DB through Linq2Sql as well. Is the Table reference in the BindingContext from the same database context as the one used for updates?
Vitalik
A: 

My ultimate solution was to create two methods to bind and then later rebind the data:

private void bind()
{
     object dataSource = db.Projects.OrderBy(p => p.ProjectNo);
     projectNoTextBox.DataBindings.Add("Text", dataSource, "ProjectNo");
     projectNameTextBox.DataBindings.Add("Text", dataSource, "ProjectName");
     //etc.
}
private void rebind()
{
     projectNoTextBox.DataBindings.Clear();
     projectNameTextBox.DataBindings.Clear();
     //etc.
     bind();
}

In the load form method I would bind the data and then after a user created or deleted a project I would rebind data.

My experience with .Net data binding is that it's a big confusing black box. I think that if I completely understood it, it would save me soooo much time - after all, ever time I learn something new about data binding, the length of my GUI code gets cut in half! However I often find myself clueless about why I'm getting certain aberrant behavior. Even with this... I bet there's some easier way to do it.

John Berryman