I have an small (probably dumb) issue with databinding. I try to bind a List
List<double> _measuredValues = new List<double>();
to a winforms ListBox.
In Form_Load I set:
lstMeasuredValues.DataSource = _measuredValues;
When I update the values, nothing appears?!
_measuredValues.Add(numBuffer);
One thing I thought about is a data type issue. But how do I change the type just to change it into a string?
lstMeasuredValues.DataSource = _measuredValues.ToString().ToList();
Another reason might be that the upper line of code is within another thread. But I think this should not be the problem.
How can I bind this list?
When I update the values, nothing appears?!
_measuredValues.Add(numBuffer);
In order to allow UI to reflect the data source modifications, the data source must provide some sort of a change notification. WinForms list data binding infrastructure uses ListChanged event of the IBindingList Interface. There is a standard provided BindingList<T> class which can be used instead of List<T> to get the desired behavior. All you need is changing this line
List<double> _measuredValues = new List<double>();
to
BindingList<double> _measuredValues = new BindingList<double>();
Another reason might be that the upper line of code is within another thread. But I think this should not be the problem.
That's not good. You must make sure you don't do that because ListChanged event is expected to be raised on the UI thread.
The better way is to clear the items and assign the DataSource again:
lstMeasuredValues.Items.Clear()// clear all items
lstMeasuredValues.DataSource = _measuredValues;
Or even you can define your own refresh function and call like the following:
public void RefreshList()
{
lstMeasuredValues.Items.Clear()// clear all items
lstMeasuredValues.DataSource = _measuredValues;
}
And call them when ever you need to refresh the list:
_measuredValues.Add(numBuffer);
RefreshList();
// Add more values
RefreshList();
The problem is that the common List isn't the right choice for data binding. You should use BindingList if you want to keep updated the ListBox.
Try using it this way:
BindingList<double> bindList = new BindingList<double>(_measuredValues);
lstMeasuredValues.DataSource = bindList;
Keep in mind that when you add a new item in _measuredValues you have to manually refresh the binding, as far as I now, like this:
bindList.ResetBindings();
You could use a BindingList<double> as DataSource of your Listbox
List<double> _measuredValues = new List<double>();
BindingList<double> bindList = new BindingList<double>(_measuredValues);
lstMeasuredValues.DataSource = bindList;
Now everytime you need to add an element use the bindList variable and your listbox will update automatically as well as your _measuredValues list
One of the simplest way to do it is by putting:
lstMeasuredValues.DataSource = null; //the cheapest, trickiest, but the most important line
lstMeasuredValues.DataSource = _measuredValues;
Whenever your _measuredValues element is updated
All you need to do it to refresh the list after updating:
lstMeasuredValues.Refresh();
Related
So I want to be able to pass a combobox from one form to another as its the only things that remains the same. When I do it, is passes fine, has the correct items, however when I open the drop down there are no items, any idea why?
Hmmm, I don't know why that is, but what you might try doing is the following:
Rather than just passing in the entire combobox, just pass in the items from the previous combobox, and then make a new combobox on the form you are trying to pass it to, then populate it with the items you previously passed in as a parameter. Hope this helps!
I have now tried doing this and it now contains the items as it should
foreach (var loc in locations.Items)
Location_Selector.Items.Add(loc.ToString());
Location_Selector.SelectedIndex = locations.SelectedIndex;
But just setting one combo box to equal the other does not work, which makes no sense to me
Location_Selector = locations;
It is probably just easier to pass the items like this:
List<String> items = new List<string>();
items.AddRange(comboBox1.Items.Cast<String>());
int index = comboBox1.SelectedIndex;
Form2 form2 = new Form2();
form2.comboBox1.Items.AddRange(items.ToArray<object>());
form2.comboBox1.SelectedIndex = index;
form2.Show();
So you'd get the items to a list, then access a combobox on the next form and add the list to it. This will also copy the selected index too.
You could copy the ComboBox over, but it's more practical to just copy the items over.
So I have a databound listbox bound to a list produced from my entity:
myListbox.Datasource = myEntity.ToList();
That works fine. My question is, what is the 'correct' way to add a new element to the entity and have it reflected in my listbox?
Currently, I do this:
myEntity.Add(newItem);
myListbox.Datasource = myEntity.ToList();
Surely there is a better way than resetting the datasource each time?
try this, DataBind() will binds a data source to the invoked server control and all its child controls.
myListbox.DataBind()
Please try this:
myListbox.ResetBindings();
See https://msdn.microsoft.com/en-us/library/system.windows.forms.control.resetbindings%28v=vs.110%29.aspx
I have a DataGrid in WPF (a class that extends DataGrid), and I would like to edit the items in it. But of course I am getting the following error:
Operation is not valid while ItemsSource is in use.
Access and modify elements with ItemsControl.ItemsSource instead.
I have tried changing the itemsSource of the DataGrid, and then adding the items, but I still get the same error. Something like:
public class MyDG:DataGrid{
public void add(){
List<TimesheetRecord> records = new List<TimesheetRecord>();
foreach(TimesheetRecord rec in this.Items){
records.Add(rec);
}
//DO SOME STUFF, ADD MORE ITEMS TO records
ItemCollection col = this.Items;
this.ItemsSource = records;
col.Clear();
foreach(TimesheetRecord rec in records){
col.add(red);//exception thrown here
}
this.ItemsSource = col;
}
}
I don't understand why I am getting that error, when I have already changed the itemsSource to a different list...?
I can't (easily) add the items to the list which is originally bound as the itemsSource, because that list exists in a different class. Would it be best for me to just have a global variable in the MyDG class that is List<TimesheetRecord> myItems = new List<TimesheetRecord>(); and then in the constructor for MyDG go this.ItemsSource = myItems
Or do you have any other suggestions how I should go about doing this? I am open to anything, as this is the first time I have used databinding, so I am probably doing something wrong...
Decalre records collection as:
ObservableCollection<TimesheetRecord> records = new ObservableCollection<TimesheetRecord>();
and keep it data-bound to the DataGrid. Manipulate records collection as needed, data binding will take care of keeping UI in sync with the collection.
You have to choose whether to use Items or ItemsSource, you can't use both interchangably. Attempting to modify Items while using ItemsSource assumes an implicit conversion that isn't supported, hence the error.
In this case, it seems like the best approach might be to just set Items and add to that collection directly. To use ItemsSource, you'd need to, exactly as you wrote, pass a reference to the ItemsSource collection (List<TimesheetRecord>) in to your DataGrid class.
Once you assign "records" to the ItemsSource, you've already updated your collection. There's no need to manually add items to the dataGrid.Items collection.
I have a combobox on my form that is bound to a generic list of string like this:
private List<string> mAllianceList = new List<string>();
private void FillAllianceList()
{
// Add alliance name to member alliance list
foreach (Village alliance in alliances)
{
mAllianceList.Add(alliance.AllianceName);
}
// Bind alliance combobox to alliance list
this.cboAlliances.DataSource = mAllianceList;
}
The user may then add or remove items in the combobox.
I have read elsewhere that by simply adding or removing the item in the generic list, the contents of the combobox should automatically be updated; same thing should occur if I use Sort() on it.
But for some reason, I cannot make this work. I can see the combobox's DataSource property is correctly updated as I add/remove/sort items, but the contents displayed in the combobox are not those in the DataSource property.
I am surely missing something or doing something wrong.
Thanks in advance!
EDIT:
The answer I chose solved the issue for adding and removing, but a BindingList object cannot be sorted, and this is necessary for me. I've found a solution where a custom class is built by inheriting BindingList and adding sorting capabilities, but I would like to know if there's an easier solution in my case.
Any suggestions on how to solve this easily?
The easiest way around this would be to simply use a BindingList like so:
private List<string> mAllianceList = new List<string>();
private BindingList<string> bindingList;
private void FillAllianceList()
{
// Add alliance name to member alliance list
foreach (Village alliance in alliances)
{
mAllianceList.Add(alliance.AllianceName);
}
bindingList = new BindingList<string>(mAllianceList);
// Bind alliance combobox to alliance list
this.cboAlliances.DataSource = bindingList;
}
Then, from here on out, just deal with the binding list to add and remove items from there. That will remove it both from the List and from the ComboBox.
EDIT: To answer your question regarding sorting, I guess the easiest (but possibly "hacky" way to do it would be something like this:
mAllianceList.Sort();
bindingList = new BindingList<string>(mAllianceList);
this.cboAlliances.DataSource = bindingList;
So basically, after you sort, you create a new binding list and reset the data source. Maybe there's a more elegant way to go about this, however this should work.
How to remove selected items from ListBox when a datasource is assigned to it in C#?
When trying to remove, got error
"Items collection cannot be modified when the DataSource property is set."
But when i try to remove item from datasource (datatable) ,
it thorws error as "datarow is not in current row collection".
Find that item in the DataSource object and remove it, then re-bind the ListBox.
EDIT:
Here's how you delete from a DataTable as your DataSource, regardless of the .NET version.
DataRowView rowView = listBox.SelectedItem as DataRowView;
if (null == rowView)
{
return;
}
dt.Rows.Remove(rowView.Row);
I haven't tried with anything other than WinForms DataGridViews, but I highly recommend BindingListView, which is both faster than DataTables/Views and allows you to bind generic List<T>s as your DataSource.
Alternatively, use a list that implements IBindingList or inherits from BindingList. When objects are added or removed from a Binding List, any controls bound to it are automatically notified of the change and will update themselves accordingly. If you are using BindingList and your class also implements INotifyProperty changed, Any changes to class properties will also be updated automatically in the databinding control. For example, if a column in a datagrid(view) is bound to a property, "Name", and you change "Name" in the datasource, the datagrid will automatically update. If you add a new item to the datasource, the datagrid will update automatically. Binding List also supports notification in the other direction. If a user edits the "Name" field ina datagrid, the bound object will be updated automatically. Going off topic slightly, if you go a little further and impliment "SupportsSortingCore" and the associated methods in BindingList, you can add automatic sorting to your data. Clicking on a columnm header will automatically sort the list and display the header sort direction arrow.
If the ListBox has a datasource assigned, you must remove items from the datasource and then rebind the ListBox
You need to modify the data source rather than the Items collection of the control. Depending on what kind of data source you are binding to, there are going to be different things you have to do so that your UI updates.
The best way is find a collection that fits your needs and implements IBindingList or IBindingListView. Those two interfaces implement even handlers that listen for a CollectionChanged event and update your UI accordingly.
If your collection doesn't support those interfaces, you're going to have to re-bind your data source every time somebody adds/removes an item.
when you get the message "Items collection cannot be modified when the DataSource property is set."
setting the datasource to something else, empty list or null does not help when
the code initializecomponent is not completed.
to avoid that error, one must do the change of datasource or the item list during or after form load.
I know it does not seem to make sense. Hoever, the visual studio designer will generate code in the form designer.cs or vb that will add items to the listbox if any code that changes the items is found before end of initialize components
While Chris Doggett posted a valid solution, I ran into problems while using it. By using that method it was not allowing a subsequent GetChanges(DataRowState.Deleted) to work properly.
To better solve my problem, I only had to change a single line - the last line.
DataRowView rowView = listBox.SelectedItem as DataRowView;
if (null == rowView)
{
return;
}
rowView.Row.Delete();
This allowed my GetChanges call to work properly.
This worked for me
DataTable temp = (DataTable)lstBlocks.DataSource;
temp.Rows.RemoveAt(position);
its vary simple , assign a new blank value to listbox
eg..
Dim ABC As New List(Of String)()
ListBox1.DataSource = ABC
ListBox implementation is bugged, you need to create a new data source instance for the component for it to recognize a change.
Eg:
ActivitiesList.DataSource = _activities;
_activities = new List<Activity>(_activities);
_activities.Remove((Activity)ActivitiesList.SelectedItem);
ActivitiesList.DataSource = _activities;