I have a C# winform that uses a listbox with a bound list for the datasource. The list is created from a text file on the computer. I'm trying to create a "Remove all" button for this listbox and am having a little trouble.
First, here is the relevant code:
private void btnRemoveAll_Click(object sender, EventArgs e)
{
// Use a binding source to keep the listbox updated with all items
// that we add
BindingSource bindingSource = (BindingSource)listBox1.DataSource;
// There doesn't seem to be a method for purging the entire source,
// so going to try a workaround using the main list.
List<string> copy_items = items;
foreach (String item in copy_items)
{
bindingSource.Remove(item);
}
}
I've tried foreaching the bindingSource, but it gives an enumeration error and just won't work. As far as I can tell, there's not code to just purge an entire source, so I tried going through the List itself and removing them via the item name, but that doesn't work either since the foreach actually returns an object or something and not a string.
Any suggestions on how to do this?
You can do it directly by typing
listBox1.Items.Clear();
If you bound the Listbox to a BindingSource using some generic List then you can just do this:
BindingSource bindingSource = (BindingSource)listBox1.DataSource;
IList SourceList = (IList)bindingSource.List;
SourceList.Clear();
On the other handy, holding a reference to the underlaying List in your Form, Viewmodel or whatever would do the trick aswell.
EDIT:
This only works if your List is a ObservableCollection. For normal List you can try call ResetBindings() on the BindingSource to enforce a refresh.
Related
I have a ComboBox bound to a List via a DataSource. For some reason, when the datasource items change, the items in the combo box don't seem to automatically update. I can see in the debugger the datasource contains the correct items.
There are lots of answers on StackOverflow about this, but most are either unanswered, don't work for me, or require changing from using Lists to BindingLists which I cannot do this instance due to the volume of code which uses methods BindingLists don't have.
Surely there must be a simple way of just telling the ComboBox to refresh it's items? I can't believe this doesn't exist. I already have an event which fires when the Combo needs to be updated, but my code to update the values has no effect.
Combo declaration:
this.devicePortCombo.DataBindings.Add(
new System.Windows.Forms.Binding("SelectedValue",
this.deviceManagementModelBindingSource, "SelectedDevice", true,
DataSourceUpdateMode.OnPropertyChanged));
this.devicePortCombo.DataSource = this.availableDevicesBindingSource;
Code to update the combobox:
private void Instance_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "AvailableDevices")
{
// Rebind dropdown when available device list changes.
this.Invoke((MethodInvoker)delegate
{
devicePortCombo.DataSource = AvailableDevicesList;
devicePortCombo.DataBindings[0].ReadValue();
devicePortCombo.Refresh();
});
}
}
You are not binding the DataGridview's DataSource to same BindingSource object in your case this.availableDevicesBindingSource which bound first time. but later you are binding to different object AvailableDevicesList. again you are using another binding source for SelectedValue i.e this.deviceManagementModelBindingSource.
use one BindingSource only, may solve your issue
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 want to cache a DataGridView row between 'refreshes' i.e. between a Rows.Clear() and a Columns.Clear(). However it seems that calling the Clear() methods does not unbind the data from the DataGridView instance, An example,
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataGridViewRow cachedRow = new DataGridViewRow();
private void button1_Click(object sender, EventArgs e)
{
this.dataGridView1.Rows.Clear();
this.dataGridView1.Columns.Clear();
DataGridViewColumn aColumn = new DataGridViewTextBoxColumn();
this.dataGridView1.Columns.Add(aColumn);
this.dataGridView1.Rows.Add(cachedRow);
}
}
This is done on a Form containing a DataGridView and a Button. Clicking the button twice gives the "Row provided already belongs to a DataGridView" error.
There has been some discussion online about this that suggests that it may be a bug, however this was around 2004.
Once a row is part of a gridview, you can't re-add it. The row itself keeps track of what DataGridView it is in. I would suggest making a copy of the cached row and adding the copy to the view. Since you make a new copy each time it won't be in the view. Alternatively, you can go through and remove only those rows that have not been cached from the view, leaving the cached rows behind so that you don't need to re-add it.
Clone it to a DataRow() and then DataTable.ImportRow to the originating DataTable.
I'm not sure why you'd want this behviour? You should only remove the rows in the grid that you want to remove.
You should look into implementing ObservableCollection and a Binding component. This way, if an item is removed from your object model, then it is automatically removed from the grid. This saves you having to perform what sounds like manual data binding and avoids this problem altogether.
If you're using DataSet or typed DataSets, then the observable functionality is already implemented for you - you just need to bind the datatable to the grid. If you have a table object in memory, you'll notice that you can load another one, then use the DataTable.Merge function to combine the results.
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;