NastyEbilPiwate
NastyEbilPiwate

Reputation: 28

How do I get bound winforms controls to refresh when their datasource is updated?

I'm very new to working with databases in C# (but not C# itself) and the whole concept of data binding, so please bear that in mind. I'm also using SQL Server CE if that affects this.

I'm trying to use a strongly-typed dataset built with VS2010 to access an SQL Server CE database, and bind WinForms controls to it to display data. I can get the controls bound fine, and they show the data that's currently in the database no problem. I can also insert new data into the database, and if I restart the application the inserted data shows up in the controls (specifically a ComboBox, but I'll be using more in the future).

The problem is that the new rows don't show up at all until I restart the app, and my understanding of data binding is that the controls should automagically update themselves. I've read about INotifyPropertyChanged but I'm not sure if it's the right thing to use here, and if it is, how do I use it for row insertions?

I'm binding the combobox like this:

DataSet.tagDataTable tagdata = new tagTableAdapter().GetData();
comboBox1.DataSource = tagdata;
comboBox1.DisplayMember = tagdata.tagnameColumn.ColumnName;
comboBox1.ValueMember = tagdata.tagIDColumn.ColumnName;

and inserting like this:

Guid g = Guid.NewGuid();
new tagTableAdapter().Insert(g, Name)

where Name is just a string pulled from a textbox.

Thanks.

EDIT: I should mention that the DB table I'm using is called tag, with two columns, tagID and tagname. tagID is a GUID, tagname is a varchar.

Upvotes: 1

Views: 1321

Answers (2)

Brad Rem
Brad Rem

Reputation: 6026

What you are doing with your TableAdpater.Insert is inserting your data directly into your database and you're circumventing any notifications in your application. If you do that then you have to do what iefpw said and that was to reload your datatable and rebind your controls.

An alternate method would be to add a row into your datatable. You can try something like this:

// retrieve the datatable from the control
DataSet.tagDataTable tagdata = comboBox1.DataSource as DataSet.tagDataTable;
// create a new row and fill in the data
var dr = tagdata.NewRow();
dr["tagid"] = Guid.NewGuid();
dr["tagname"] = Name;
// actually add it to the table
tagdata.Rows.Add(dr);

At this point you've added it to your DataTable and your combobox will automatically update, but the caveat is that it has not been written to your database so you'll need to make sure at some point you save to your database.

Upvotes: 2

iefpw
iefpw

Reputation: 7042

You should bind the data again and refresh the controls again like you did the first time. It doesn't just display the data. It is mechanic. It is not realtime.

Upvotes: 0

Related Questions