Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a listbox that I've binded to a List<t> collection object but when I make changes in the List<t> object it's not being reflected in the my listbox. What am I doing wrong here?

Oh, by the way I'm using windows form. Here's my code:

class MyDataObject
{
   List<string> data;

   public MyDataObject()
   {
      data = new List<string>() {"abc","rst","xyz"};
   }

   public List<string> Data
   {
     get{return data;}
     set{data = value;}
   }
}


// Windows Form section

MyDataObject datObj = MyDataObject();

public Form()
{
   Initialization();
  
   listbox1.DataSource = datObj.Data;
   listbox1.DisplayMember = "Data";
}

void button1_Click(object sender, EventArgs e)
{
  string newData = textbox1.Text;
  datObj.Data.Add(newData);

  listbox1.Refresh();
}
</string></string></string>

The listbox initially shows the dataObj's Data items but when I add new data to the textbox and pass it to my dataObject and click button1 it's not displaying in my listbox which I thought was binded to my datObj's Data memeber?
Posted
Updated 5-Dec-11 9:53am
v2
Comments
RaviRanjanKr 5-Dec-11 15:54pm    
[Edited]Code is wrapped in "pre" tag[/Edited]
d.allen101 5-Dec-11 15:57pm    
what's the correct way to tag my code? is it: [/code] [code]?
RaviRanjanKr 5-Dec-11 16:06pm    
No "Pre" tag is much better for wrap your codes. just select your codes and click on pre tag.

Instead of a List<t>, use an ObservableCollection<t> to get notified of insertions, the List itself does not notify changes.
 
Share this answer
 
Hi,

Try using BindingList<t> in stead or List<t>. the list does not fire an changed update and as such your list box will not be updated.

Regards, AT
 
Share this answer
 
You need to rebind the listview to refresh its values.

Regards,
Eduard
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900