chart not updating when changing the value of displaymember - c#

I have an Modernui Piechart binded to an ObservableCollection.
If I change the name of an item it is not updating, but if I change the value of on item then it will be updated properly(add/remove works fine).
Chart XAML :
<chart:PieChart Grid.RowSpan="2"
Style="{StaticResource MinimalChartStyle}"
ChartTitle="Minimal Pie Chart"
ChartSubTitle="Chart with fixed width and height"
>
<chart:PieChart.Series>
<chart:ChartSeries
SeriesTitle="Categories"
DisplayMember="CategoryName"
ValueMember="CategoryExpenseLimit"
ItemsSource="{Binding Path=Cat}" />
</chart:PieChart.Series>
</chart:PieChart>
Code where I add item: (this updates the chart properly when adding item)
TransactionCategoryModel category = new TransactionCategoryModel() { TheCategory = { CategoryName = CategoryName, CategoryExpenseLimit = (decimal)CategoryExpenseLimit }};
context.TransactionCategories.Add(category.TheCategory);
context.SaveChanges();
var obs = Application.Current.Resources["CategoryObs"] as ObservableCollection<CategoryViewModel>;
obs.Add(new CategoryViewModel(category));
Code to edit an Item :(retrieve it from the database and update it then update the observable collection as well)
var category = context.TransactionCategories.Where(i => i.CategoryId == this.CategoryId).First();
var tCategory = new TransactionCategoryModel() { TheCategory = category };
tCategory.TheCategory.CategoryId = (int)CategoryId;
tCategory.TheCategory.CategoryName = CategoryName;
tCategory.TheCategory.CategoryExpenseLimit = (decimal)CategoryExpenseLimit;
context.SaveChanges();
var obs = Application.Current.Resources["CategoryObs"] as ObservableCollection<CategoryViewModel>;
var x = obs.Where(i => i.CategoryId == this.CategoryId).FirstOrDefault();
CategoryViewModel cvm = new CategoryViewModel(tCategory);
x = cvm;
With this I edit an item. Problem is if I edit it and change the name the chart does not update the displaymember, but if I also change the expenselimit(this is the valuemember of the chart) then the chart will update properly.
The fact that the name does not update happens only with the chart. I made a datagrid in another view and binded the Observablecollection and the data grid updates properly even when I change only the name.
In the ViewModel of the chart :
private ObservableCollection<CategoryViewModel> cat;
public ObservableCollection<CategoryViewModel> Cat
{
get { return cat; }
set
{
cat = value;
OnPropertyChanged("Cat");
}
}
And in the constructor:
if (cat == null)
cat = new ObservableCollection<CategoryViewModel>();
cat = Application.Current.Resources["CategoryObs"] as ObservableCollection<CategoryViewModel>;
And when I the app starts : to retrieve the values
private void GetCategories()
{
List<CategoryViewModel> categories = new List<CategoryViewModel>();
using( var context = new Ents())
{
foreach(var item in context.TransactionCategories)
{
TransactionCategoryModel tcm = new TransactionCategoryModel() { TheCategory = item };
categories.Add(new CategoryViewModel(tcm));
}
}
ObservableCollection<CategoryViewModel> Categories = new ObservableCollection<CategoryViewModel>(categories);
Application.Current.Resources.Add("CategoryObs", Categories);
}

..edit it and change the name the chart does not update the
displaymember
Two things, an ObservableCollection is primarily a signaler for when items are added or removed from its list. It doesn't help binding or processing of items which are edited.
Secondly for any changes of individual items to be noticed, the property which it is bound needs to signal its change. That signaling is done when the class it resides on implements INotifyPropertyChange and it calls an OnPropertyChanged method with its name.
So looking at your code, you are learning I get that, the code
public ObservableCollection<CategoryViewModel> Cat {
get { return cat; }
set { cat = value; OnPropertyChanged("Cat"); }}
Only signals when a new observable collection is assigned. Now that may be helpful in certain situations, such as swapping in and out of lists (I do it to change combobox drop down selections) but in your case its a one trick pony which is useful to the chart and needed, but the chart doesn't care you have an ObservableCollection. Because one has to purposefully subscribe to the ObservableCollection events to do anything. Frankly you could and should just use a List<CategoryViewModel> instead.
chart does not update the displaymember
Does the property CategoryName on the class CategoryViewModel call an PropertyChange because CategoryViewModel implements INotifyPropertyChanged?
Note...even it if does, the charting tool may not be subscribing to the change notification, because its a reporting tool and wasn't designed as such. If that is the case, you may need to wink the whole CategoryViewModel instance in and out (remove it then re-add it) to make the reporting chart control show the change in the name.

Related

How can I change all of the data in an observable collection so functions using this can notice the change that happens?

I have this code:
public ObservableCollection<CVM> SObservable{ get; set; }
this.scores = App.DB.GetCardFace(0);
this.SObservable = new ObservableCollection<CVM>(this.scores);
I then assign this as a data source:
this.columnSeries = new ColumnSeries() {
ItemsSource = SObservable
};
chart.Series.Add(this.columnSeries);
My chart displays correctly
Now I change the data:
this.scores = App.DB.GetCardFace(1);
but nothing happens to the chart. I suspect the SObservable contents are not changing.
Can someone give me advice on how I should go about changing the contents of the SObservable so it triggers a change that can be picked up by the chart code.
an ObservableCollection does not contain any references to the data that was used to populate it in it's constructor, so a change to that original data will not be reflected in the ObservableCollection
SObservable.Clear();
foreach(var s in scores)
{
SObservable.Add(s);
}

ObservableCollection<> not loading properly

I am trying to implement filtering on an ObservableCollection<>. My current ObservableCollection<Payee> is working fine as an ItemsSource on a GridView. I added a second ObservableCollection<Payee> called FilteredPayees to use as the ItemsSource. For some reason, when I try to filter the items, the GridView is showing up blank.
Here is the code I'm using:
private void FilterPayees()
{
if (!_settings.ShowInactivePayees)
{
var filtered = _payees.Where(p => p.IsOpen == true);
_filteredPayees = new ObservableCollection<Payee>(filtered);
}
else
{
_filteredPayees = _payees;
}
this.FilteredPayees = _filteredPayees;
}
Basically, if the ShowInactivePayees setting is turned off, it should filter out the inactive payees. If it is on, then just use the full _payees collection. The strange thing, if I change the last line to:
this.FilteredPayees = _payees;
then the GridView will display all of the payees, just as it should if the "show inactive payees" settings is turned on. I set breakpoints and the _filteredPayees collection has 35 items in it (or 65 when not filtering). It does not appear to be any type of "object not set to an instance of an object" or anything like that. Is there some reason that
this.FilteredPayees = _payees;
would work, but
_filteredPayees = _payees;
this.FilteredPayees = _filteredPayees;
would not?
EDIT
I was able to get it to work for now by getting rid of the FilteredPayees property. I just filter the original Payees collection in the OnNavigatedTo() event handler, which is exactly the same place where I was calling FilteredPayees().
// load payees
var payees = await _payeesRepository.LoadAllAsync();
if (!_settings.ShowInactivePayees)
{
payees = payees.Where(p => p.IsOpen);
}
payees = payees.OrderBy(p => p.CompanyName);
this.Payees = new ObservableCollection<Payee>(payees);
The only part I added was the if (!_settings.ShowInactivePayees) ... block. My reasoning to use the FilteredPayees property was so that I could have the full collection loaded in the Payees property and not need to reload if the ShowInactivePayees setting was changed - just change the filter of the collection.
You are assigning a new object to FilteredPayees property, so GridView has to be notified that the property FilteredPayees is changed. There should be RaisePropertyChanged("FilteredPayees") or your notification code in the setter of FilteredPayees.
Also, the binding mode of GridView.ItemsSource should not be BindingMode.OneTime.
For filtering a collection in WPF it may be easier to use ICollectionView. For example:
public class Foo
{
private List<Payee> _payees;
private ICollectionView _filteredPayees;
public ICollectionView FilteredPayees
{
get { return _filteredPayees; }
}
public Foo()
{
_payees = GetPayees();
_filteredPayees = CollectionViewSource.GetDefaultView(_payees);
_filteredPayees.Filter = FilterPayees;
}
private bool FilterPayees(object item)
{
var payee = item as Payee;
if (payee == null)
{
return false;
}
if (_settings.ShowInactivePayees)
{
return true;
}
return payee.IsOpen;
}
}
You can bind the property FilteredPayees like any other property. The advantage is, that you don't need two properties and you can avoid the logic of which collection you want to bind.
_filteredPayees = new ObservableCollection<Payee>(filtered);
Here you create a completely new object, and that's not something ObservableCollection can automatically observe. The possible solution is to set ItemsSource on your GridView again after this line.

Property bound to DataGrid's SelectedItem does not change its child properties when CellEditEnding is fired

I have a DataGrid which looks like:
<DataGrid Grid.Row="3" Grid.Column="1" ItemsSource="{Binding Purchases}" SelectionMode="Single" SelectionUnit="FullRow"
SelectedItem="{Binding SelectedPurchase, Source={x:Static ex:ServiceLocator.Instance}}"
AutoGenerateColumns="False" CanUserAddRows="False">
<e:Interaction.Triggers>
<e:EventTrigger EventName="CellEditEnding">
<e:InvokeCommandAction Command="{Binding DataContext.CellEditEndingCommand,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Page}}}"/>
</e:EventTrigger>
</e:Interaction.Triggers>
<DataGrid.Columns>
.......
........
<DataGrid.Columns>
</DataGrid>
Property SelectedPurchase looks like:
private Purchase _selectedPurchase;
public Purchase SelectedPurchase
{
get
{
return _selectedPurchase;
}
set
{
_selectedPurchase = value;
NotifyPropertyChanged("SelectedPurchase");
}
}
CellEditEndingCommand
public ICommand CellEditEndingCommand { get; set; }
private void CellEditEndingMethod(object obj)
{
XDocument xmlPurchases = XDocument.Load(DirectoryPaths.DataDirectory + "Purchases.xml");
var currentPurchaseInData = (from purchase in xmlPurchases.Element("Purchases").Elements("Purchase")
where Convert.ToInt32(purchase.Attribute("Id").Value) == ServiceLocator.Instance.SelectedPurchase.Id
select purchase).FirstOrDefault();
currentPurchaseInData.SetElementValue("CreditorId", ServiceLocator.Instance.SelectedPurchase.Creditor.Id);
currentPurchaseInData.SetElementValue("AnimalId", ServiceLocator.Instance.SelectedPurchase.Animal.Id);
currentPurchaseInData.SetElementValue("QuantityInLitre", ServiceLocator.Instance.SelectedPurchase.Litre);
currentPurchaseInData.SetElementValue("FAT", ServiceLocator.Instance.SelectedPurchase.FAT);
currentPurchaseInData.SetElementValue("RatePerLitre", ServiceLocator.Instance.SelectedPurchase.RatePerLitre);
xmlPurchases.Save(DirectoryPaths.DataDirectory + "Purchases.xml");
}
Now If I change any value in DataGridCell and then I hit Enter CellEditEndingCommand is fired and CellEditEndingMethod is fired. But If I keep a breakpoint inside CellEditEndingMethod and take a look at it, then I can see that Values of any property of SelectedPurchase does not change to new values.
Let me give an example to explain the above line more correctly:
When I keep a breakpoint on any line inside CellEditEndingMethod and take a look at Properties like Litre, FAT etc., these properties values does not change. I mean I expect the property to take new value but it holds old value. Also, In view I can see the new values but in XML file there are still old values.
Update:
Purchases = new ObservableCollection<Purchase>(
from purchase in XDocument.Load(DirectoryPaths.DataDirectory + "Purchases.xml")
.Element("Purchases").Elements("Purchase")
select new Purchase
{
Id = Convert.ToInt32(purchase.Attribute("Id").Value),
Creditor = (
from creditor in XDocument.Load(DirectoryPaths.DataDirectory + "Creditors.xml")
.Element("Creditors").Elements("Creditor")
where creditor.Attribute("Id").Value == purchase.Element("CreditorId").Value
select new Creditor
{
Id = Convert.ToInt32(creditor.Attribute("Id").Value),
NameInEnglish = creditor.Element("NameInEnglish").Value,
NameInGujarati = creditor.Element("NameInGujarati").Value,
Gender = (
from gender in XDocument.Load(DirectoryPaths.DataDirectory + #"Basic\Genders.xml")
.Element("Genders").Elements("Gender")
where gender.Attribute("Id").Value == creditor.Element("GenderId").Value
select new Gender
{
Id = Convert.ToInt32(gender.Attribute("Id").Value),
Type = gender.Element("Type").Value,
ImageData = gender.Element("ImageData").Value
}
).FirstOrDefault(),
IsRegisteredMember = creditor.Element("IsRegisteredMember").Value == "Yes" ? true : false,
Address = creditor.Element("Address").Value,
City = creditor.Element("City").Value,
ContactNo1 = creditor.Element("ContactNo1").Value,
ContactNo2 = creditor.Element("ContactNo2").Value
}
).FirstOrDefault(),
Animal = (
from animal in XDocument.Load(DirectoryPaths.DataDirectory + #"Basic\Animals.xml")
.Element("Animals").Elements("Animal")
where animal.Attribute("Id").Value == purchase.Element("AnimalId").Value
select new Animal
{
Id = Convert.ToInt32(animal.Attribute("Id").Value),
Type = animal.Element("Type").Value,
ImageData = animal.Element("ImageData").Value,
Colour = animal.Element("Colour").Value
}
).FirstOrDefault(),
Litre = Convert.ToDouble(purchase.Element("QuantityInLitre").Value),
FAT = Convert.ToDouble(purchase.Element("FAT").Value),
RatePerLitre = Convert.ToDouble(purchase.Element("RatePerLitre").Value)
}
);
The CellEditEnding Event is not meant to update the datarow but to validate the single cell and keep it in editing mode if the content is not valid. The real update is done when the whole row is committed. Try it by adding the code in the HandleMainDataGridCellEditEnding method in http://codefluff.blogspot.de/2010/05/commiting-bound-cell-changes.html to your CellEditEndingMethod. It is good explained there. You may replace the if (!isManualEditCommit) {} by if (isManualEditCommit) return;.
UPDATE
You can extend your Purchase class by interface IEditableObject. DataGrid will call the method EndEdit() of this interface after the data has been committed and so you can do the XML stuff there. So you don't need any further buttons because a cell goes in edit mode automatically and the commit is done when you leave the row.
I think the CollectionChanged solution does not work because if you edit a dataset all changes take place inside the single object (Purchase) and not in the collection. CollectionChanged will be called by adding or removing an object to the collection
2nd UPDATE
Another try by putting it all together:
I simplified your Purchase class for demonstration:
class Purchase
{
public string FieldA { get; set; }
public string FieldB { get; set; }
}
Create a derived class to keep the real Purchase class clean:
class EditablePurchase : Purchase, IEditableObject
{
public Action<Purchase> Edited { get; set; }
private int numEdits;
public void BeginEdit()
{
numEdits++;
}
public void CancelEdit()
{
numEdits--;
}
public void EndEdit()
{
if (--numEdits == 0)
{
if (Edited != null)
Edited(this);
}
}
}
This is explained in SO WPF DataGrid calls BeginEdit on an IEditableObject two times?
And create the Purchases collection:
ObservableCollection<EditablePurchase> Purchases = new ObservableCollection<EditablePurchase>()
{
new EditablePurchase {FieldA = "Field_A_1", FieldB = "Field_B_1", Edited = UpdateAction},
new EditablePurchase {FieldA = "Field_A_2", FieldB = "Field_B_2", Edited = UpdateAction}
};
Purchases.CollectionChanged += Purchases_CollectionChanged;
private void Purchases_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (EditablePurchase item in e.NewItems)
item.Edited = UpdateAction;
}
void UpdateAction(Purchase purchase)
{
// Save XML
}
This provides that the calls to Edited are catched for all EditablePurchase elements from initialization and for newly created ones. Be sure to have the Edited property set in initializer
This is a disgrace for WPF. No DataGrid.CellEditEnded event? Ridiculous, and I didn't know about that so far. It's an interesting question.
As Fratyx mentioned, you can call
dataGrid.CommitEdit(DataGridEditingUnit.Row, true);
in a code behind CellEditEnding method. While it works, I find it's quite ugly. Not only because of having code behind (could use a behavior to circumnavigate that), but your ViewModel CellEditEndingMethod will be called twice, once for no good reason because the edit is not yet committed.
I would probably opt to implement INotifyPropertyChanged in your Purchase class (I recommend using a base class so you can write properties on one line again) if you haven't already, and use the PropertyChanged event instead:
public MyViewModel()
{
Purchases = new ObservableCollection<Purchase>();
Purchases.CollectionChanged += Purchases_CollectionChanged;
}
private void Purchases_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (Purchase item in e.NewItems)
item.PropertyChanged += Purchase_PropertyChanged;
if (e.OldItems != null)
foreach (Purchase item in e.OldItems)
item.PropertyChanged -= Purchase_PropertyChanged;
}
private void Purchase_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// save the xml...
}
You will not get any CollectionChanged event before DataGrid is changing the collection. And this does not before happen a dataset is committed.
If you press 'Enter' in a cell you change the value of this cell in a kind of copy of the real dataset. So it is possible to skip the changes by rollback. Only after finishing a row e.g. by changing to another row or direct commit your changed data will be written back to the original data. THEN the bindings will be updated and the collection is changed.
If you want to have an update cell by cell you have to force the commit as in the code I suggested.
But if you want to have a puristic MVVM solution without code behind you have to be content with the behavior DataGrid is intended for. And that is to update after row is finished.

WPF ListView: Changing ItemsSource does not change ListView

I am using a ListView control to display some lines of data. There is a background task which receives external updates to the content of the list. The newly received data may contain less, more or the same number of items and also the items itself may have changed.
The ListView.ItemsSource is bound to an OberservableCollection (_itemList) so that changes to _itemList should be visible also in the ListView.
_itemList = new ObservableCollection<PmemCombItem>();
_itemList.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged);
L_PmemCombList.ItemsSource = _itemList;
In order to avoid refreshing the complete ListView I do a simple comparison of the newly retrieved list with the current _itemList, change items which are not the same and add/remove items if necessary. The collection "newList" contains newly created objects, so replacing an item in _itemList is correctly sending a "Refresh" notification (which I can log by using the event handler OnCollectionChanged of the ObservableCollection`)
Action action = () =>
{
for (int i = 0; i < newList.Count; i++)
{
// item exists in old list -> replace if changed
if (i < _itemList.Count)
{
if (!_itemList[i].SameDataAs(newList[i]))
_itemList[i] = newList[i];
}
// new list contains more items -> add items
else
_itemList.Add(newList[i]);
}
// new list contains less items -> remove items
for (int i = _itemList.Count - 1; i >= newList.Count; i--)
_itemList.RemoveAt(i);
};
Dispatcher.BeginInvoke(DispatcherPriority.Background, action);
My problem is that if many items are changed in this loop, the ListView is NOT refreshing and the data on screen stay as they are...and this I don't understand.
Even a simpler version like this (exchanging ALL elements)
List<PmemCombItem> newList = new List<PmemCombItem>();
foreach (PmemViewItem comb in combList)
newList.Add(new PmemCombItem(comb));
if (_itemList.Count == newList.Count)
for (int i = 0; i < newList.Count; i++)
_itemList[i] = newList[i];
else
{
_itemList.Clear();
foreach (PmemCombItem item in newList)
_itemList.Add(item);
}
is not working properly
Any clue on this?
UPDATE
If I call the following code manually after updating all elements, everything works fine
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
But of course this causes the UI to update everything which I still want to avoid.
After a change, you can use the following to refresh the Listview, it's more easy
listView.Items.Refresh();
This is what I had to do to get it to work.
MyListView.ItemsSource = null;
MyListView.ItemsSource = MyDataSource;
I know that's an old question, but I just stumbled upon this issue. I didn't really want to use the null assignation trick or the refresh for just a field that was updated.
So, after looking at MSDN, I found this article:
https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifypropertychanged?redirectedfrom=MSDN&view=netframework-4.7.2
To summarize, you just need the item to implement this interface and it will automatically detect that this object can be observed.
public class MyItem : INotifyPropertyChanged
{
private string status;
public string Status
{
get => status;
set
{
OnPropertyChanged(nameof(Status));
status = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
So, the event will be called everytime someone changes the Status. And, in your case, the listview will add a handler automatically on the PropertyChanged event.
This doesn't really handle the issue in your case (add/remove).
But for that, I would suggest that you have a look at BindingList<T>
https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.bindinglist-1?view=netframework-4.7.2
Using the same pattern, your listview will be updated properly without using any tricks.
You should not reset ItemsSource of ListView each time observable collection changed. Just set proper binding that will do your trick. In xaml:
<ListView ItemsSource='{Binding ItemsCollection}'
...
</ListView>
And in code-behind (suggest to use MVVM) property that will be responsible for holding _itemList:
public ObservableCollection<PmemCombItem> ItemsCollection
{
get
{
if (_itemList == null)
{
_itemList = new ObservableCollection<PmemCombItem>();
}
return _itemList;
}
}
UPDATE:
There is similar post which most probably will Answer your question: How do I update an ObservableCollection via a worker thread?
I found a way to do it. It is not really that great but it works.
YourList.ItemsSource = null;
// Update the List containing your elements (lets call it x)
YourList.ItemsSource = x;
this should refresh your ListView (it works for my UAP :) )
An alternative on Xopher's answer.
MyListView.ItemsSource = MyDataSource.ToList();
This refreshes the Listview because it's a other list.
Please check this answer:
Passing ListView Items to Commands using Prism Library
List view Items needs to notify about changes (done is setter)
public ObservableCollection<Model.Step> Steps
{
get { return _steps; }
set { SetProperty(ref _steps, value); }
}
and UpdateSourceTrigger need to be set in xaml
<Image Source="{Binding ImageData, UpdateSourceTrigger=PropertyChanged}" />

c# how do i refresh items in my listbox

I have a method that adds items to my listbox called refreshInterface which is called as soon as the programe starts, adding names of homeforms in the listbox using the FormItems class, here is the rereshInterface method below
public void refreshInterface()
{
//int number = 0;
foreach (DataSet1.xspGetAnalysisUsageTypesRow homeForms in myDataSet.xspGetAnalysisUsageTypes)
{
var forms = new FormItems(homeForms);
listBox1.Items.Add(forms);
}
}
The FormItems class is this below
public class FormItems
{
public DataSet1.xspGetAnalysisUsageTypesRow types { get; set; }
public FormItems(DataSet1.xspGetAnalysisUsageTypesRow usageTypes)
{
types = usageTypes;
}
public override string ToString()
{
// returns the rows that are relating to types.xlib_ID
var libtyps = types.GetxAnalysisUsageRows();
var cnt = 0;
foreach (DataSet1.xAnalysisUsageRow ty in libtyps)
{
//returns true if ty is null
bool typeNull = ty.Isxanu_DefaultNull();
// if its false, if xanu_Default is set
if (!typeNull)
{
cnt += 1;
}
}
var ret = String.Format("set {0} [Set: {1}]", types.xlib_Desc, cnt);
//return this.types.xlib_Desc;
return ret;
}
}
Each listbox (the listbox is on the left of the homeform) item has a number of reports that can be added to it, so for instance, i select an homeform from my listbox, there are 12 textboxes on the right hand side and each textbox has a pair of buttons which are Browse and Clear. If I click on the browse button a new form appears, and i select a report from that form and add it to a particular textbox, the count for that homeform should update, and i clear a textbox for a particular homeform, the count should also update.
At the moment when i debug the application, it shows me the count of each Homeform depending on the amount of reports added to the homeform, but while the programe is running, if i add a new report to a homeform, the count does not update until i restart the debug session. I was told about using a Databinding method but not sure of how i could use it here
How do i ge my listbox item to update ?
You should probably look into binding. Here is a good place to start:
http://www.codeproject.com/Articles/140621/WPF-Tutorial-Concept-Binding
If you want a GUI to respond to data changes then binding is your best friend.
You should bind List Box component source to Observable Collection, every update you do to Observable Collection will update List Box data.
Might not be exact but should give you an idea.
public void refreshInterface()
{
Dictionary<int,string> items = new Dictionary<int,string>();
//int number = 0;
foreach (DataSet1.xspGetAnalysisUsageTypesRow homeForms in myDataSet.xspGetAnalysisUsageTypes)
{
var formitem = new FormItems(homeForms);
items.Add(formitem.someprop, formitem.toString());
}
listbox.DataSource = items;
listbox.DisplayMember = "Value";
listbox.ValueMember = "Key";
}

Categories

Resources