0

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.

3
  • Added an edit, it's a Winforms project Commented Apr 25, 2016 at 10:45
  • 4
    have you tried: listBox1.DataSource = dc.MyTable.ToList() ? Commented Apr 25, 2016 at 10:45
  • Thank you, Ehsan, it works! Commented Apr 25, 2016 at 10:48

2 Answers 2

0

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; 
Sign up to request clarification or add additional context in comments.

Comments

0

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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.