Yucel
Yucel

Reputation: 2673

WinForm Controls binding to a List<T> problem

i have a List for storing my data, i try to bind its items to grid,listbox,textbox etc. but cant make it work well. Here is my code

class Survey
{
   public int Id { get; set; }
   public string Desc{ get; set; }
   public List<string> Choices { get; set; }
}

.

List<Survey> _surveyList = GetList();
BindingSource _bindingSourceSurveys = new BindingSource { DataSource=_surveyList};
dataGridView1.DataSource = _bindingSourceSurveys;
txtDesc.DataBindings.Add("Text", _bindingSourceSurveys, "Desc",false,DataSourceUpdateMode.OnPropertyChanged,string.Empty);
lstChoices.DataBindings.Add("DataSource" , _bindingSourceSurveys,"Choices" ,false,DataSourceUpdateMode.OnPropertyChanged, string.Empty); 

Now i can see items on dataGrid, selectedItem(on dataGrid) Desc property value on textBox and also can change Desc propert value from textBox.

If i add a new choice to my selectedItem List Choices like that

(_bindingSourceSurveys.Current as Survey).Choices.Add("NewChoice");

Note: I cant add to ListBox.Items because it give Exception because of i make binding to DataSource of this control.

ListBox dont show the new item, if i select a different item from dataGrid and turn back i can see the new added choice.

What is the problem here? Also Is that code is OK, its my first time to use this binding facilities.

Upvotes: 2

Views: 1350

Answers (1)

Sheng Jiang 蒋晟
Sheng Jiang 蒋晟

Reputation: 15261

Your data source does not raise events when elements gets changed. An easy fix is to change the datasource from List to BindingList.

Upvotes: 2

Related Questions