hungariandude
hungariandude

Reputation: 386

DataSource not updating, only with LINQ

I am using a LINQ To SQL class, which is initialized before the constructor (the tables are added to it, it works):

DataClasses1DataContext dc = new DataClasses1DataContext();

Then I have a listbox:

listBox1.DataSource = dc.MyTable;
listBox1.DisplayMember = "Name";
listBox1.ValueMember = "PersonID";

Then I want to add a new record:

MyTable mt = new MyTable();
mt.Name = "John Smith";
mt.PersonID = 30;
dc.MyTable.InsertOnSubmit(mt);
dc.SubmitChanges();

I want to refresh the listbox's datasource, by doing:

listBox1.DataSource = dc.MyTable;

...but the new record doesn't show up. However, if I update the datasource like this:

var q = from x in dc.MyTable select x;
listBox1.DataSource = q;

This works.

My only question is: why? I saw that some people set the DataSource to null, then back to the table, but that doesn't solve my problem.

(it's a winforms project)


listBox1.DataSource = dc.MyTable.ToList() seems to solve the problem, answered by Ehsan Sajjad in the comments.

Upvotes: 0

Views: 127

Answers (2)

Norman
Norman

Reputation: 3479

ToList() can cause performace (https://stackoverflow.com/a/15027581/4550393) issues when having lots of items. Since you don't really need ToList() in this case the better solution would be to clear the list and to rebind it thereafter:

listBox1.Items.Clear();
listBox1.DataSource = dc.MyTable;

Upvotes: 0

Manfred Radlwimmer
Manfred Radlwimmer

Reputation: 13394

When you update your datasource by assigning the exact same object, the control will never know that something changed. If you don't want to implement MVVM, MVC or something similar, you could just clear the value:

listBox1.DataSource = null;
listBox1.DataSource = dc.MyTable;

Upvotes: 0

Related Questions