dotnetmonitor.com |
|
||||||||||||
| In V1 and V1.1, when binding to objects such as
a DataSet, customers bind directly to the object (as is expected):
// DataSet is a member variable (_ds)
Services.BooksService service = new Services.BookService();
_ds = service.GetBooksByAuthor(this.AuthorTextBox.Text);
// Bind Grid (show returned results) this.authorsDataGridView.DataSource = _ds;
// Show details in simple controls this.priceLabel.DataBindings.Add("Text", _ds, "Price"); this.publishDateLabel.DataBindings.Add("Text", _ds, "PublishDate"); this.ISBNLabel.DataBindings.Add("Text", _ds, "ISBN"); This works well for simple cases but can be problematic if the source object changes. As a first attempt, many users try to re-set the bound object (see below). // First attempt, reset the DataSet
_ds = service.GetBooksByAuthor(this.AuthorTextBox.Text); Given this doesnt work, users move on re-setting all bindings: public void AuthorSelected() { DataSet ds = service.GetBooksByAuthor(this.AuthorTextBox.Text);
// Reset All Bindings ResetBindings(ds); }
public void ResetBindings(DataSet ds) { // Bind Grid (show returned results) this.authorsDataGridView.DataSource = ds;
// Show details in simple controls this.priceLabel.DataBindings.Add("Text", ds, "Price"); this.publishDateLabel.DataBindings.Add("Text", ds, "PublishDate"); this.ISBNLabel.DataBindings.Add("Text", ds, "ISBN"); } While this does work, it requires more work on the users part and cannot be setup at design time. For DataSets, users can short circuit this, but few customers discover this: // First attempt, reset the DataSet DataSet ds = service.GetBooksByAuthor(this.AuthorTextBox.Text);
_ds.Clear(); _ds.Merge(ds); The BindingSource provides a level of indirection at both design-time and run-time that alleviates the need for users to reset their bindings or merge data sets. private BindingSource _bs;
private void Initialize() { _bs = new BindingSource();
// Bind to the BindingSource (supported at design time) this.authorsDataGridView.DataSource = _bs;
// Bind to the BindingSource (supported at design time) this.priceLabel.DataBindings.Add("Text", _bs, "Price"); this.publishDateLabel.DataBindings.Add("Text", _bs, "PublishDate"); this.ISBNLabel.DataBindings.Add("Text", _bs, "ISBN"); }
public void AuthorSelected() { // Reset the BindingSource data source (resets bindings) _dc.DataSource = service.GetBooksByAuthor(this.AuthorTextBox.Text); } |
||||||||||||
|
||||||||||||