ListBox.SelectedItem is null notification - c#

I need to track current selected item in ListBox to turn off some other controls on the form when selected item become null. I try to use SelectedIndexChanged event, but it not raise when selected item is null.
Can you please advise something?
UPDATE: Selected item becomes null because i set new DataSource value with empty collection. May be it's a reason of my problem?
I need to explain. ListBox represent collection of items from database. When user add/edit/delete some item, I refresh listbox by calling this method:
private void RefreshList()
{
lbParts.DataSource = this.database.Fetch<part>(string.Empty);
}
It fetched all items from database, convert it to List<part> collection and set as ListBox DataSource.

That is incorrect. SelectedIndexChanged is raised when SelectedItem becomes null. In this case, SelectedIndex will be -1.
EDIT: you are indeed correct that when you change DataSource, you don't get SelectedIndexChanged. I would recommend explicitly setting SelectedIndex=-1 immediately before anytime you change DataSource

Perhaps handle the DataSourceChanged event as well? If the choices available in the listbox change, then I assume this is reason to perform a refresh on the forms avialable controls?

Related

How do I check if a selected item has changed from the previously selected item?

I have a listbox in my winform, when an item in the listbox is selected, a value is placed into a textbox in the same Form. There my many items in my listbox which when selected, i want the text box to be empty so i can pass in the new value. How do i check is if the user has clicked on something other their initial selected item? i get the currently selected item like this below:
var selectedItem = (ReportItems)listbox.selectedItem
You can use the SelectedIndexChanged event on your ListBox . You can create an event handler for this event to determine when the selected index in the ListBox has been changed. This can be useful when you need to display information in other controls based on the current selection in the ListBox. You can use the event handler for this event to load the information in the other controls.
See MSDN documentation: link
You can add a global variable for your ReportItems and call it 'selItem'.
After the user changed the selected Item you check the "new" selectedItem with the 'selItem'-variable.. i don't think that a listbox has a method that can check if the selection has changed from the previous one..
I'm not sure if there is a reason you're not leveraging the SelectionChanged event of the ListBox or not but you should be if you're not. Further, determining if it's different than the initially selected item should be pretty straight forward because you can save the initially selected item in a private variable in your form and compare every time the method handler for SelectionChanged fires.
Other than this, there's not much more I can suggest because your questions isn't terribly clear and there is no code to look at.
My solution was to always clear the textbox first. So as soon as a user selects an item in the listview, rather than populating the textbox straight away, clear the textbox before populating it.
clearText(); is called soon as a listbox item is clicked.
public void clearText()
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
textBox6.Clear();
textBox7.Clear();
textBox8.Clear();
textBox9.Clear();
textBox10.Clear();
textBox11.Clear();
textBox12.Clear();
}

C# Databinding SelectedIndexChanged call

I am using a SelectedIndexChanged function for a combobox to update the content of my DataGridview item. I have the combobox data bound to keep track of it's currently selected record. However, when I changed the combobox index it updates the datagridview as if the selected value was the same. This means once I have selected a different index value in the combobox, I have to select it again to run the function with the proper value.
Am I missing something here? Do I need to call the check for the current datarow selected in the combobox before calling the SelectedIndexChanged function?
Sounds like the page life cycle issue, as the datagrid will be fired before the slected index change if its in the page load event. at which point the index wont have changed so the data will be the same.

Retrieve value of most recently SelectedItem from multi-select listbox

How can I retrieve the value of a clicked item in a multi-select listbox?
Currently, if I click one item and use lstBox.SelectedValue, it will return the proper value; however, if I then click on another item, I am still shown the first item's value.
Basically, I want the value of the item most recently clicked on, regardless of whether or not it is the SelectedValue.
If it is a multiple selection listbox, you can get a collection of all the selected items by using SelectedItems instead of SelectedItem.
If you need to know the sequence in which the items were selected, or which was selected most recently, I think you would need to record if yourself by SelectedIndexChanged event.
The SelectedIndexChanged handler will get called when you select/unselect an item in the listbox.
However, it doesn't indicate which one was selected/unselected.
listbox1.SelectedItems
will contain the currently selected items and you could internally keep track of which index was most recently added.

How to remove selected items from ListBox when a DataSource is assigned to it in C#?

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;

Stuck with datagridview and combo box column

I have a typical requirement.
I have a datagridview with a combobox column(items loaded at design time). When a user selects an item from combobox, remaining rows gets updated in database based on the selectedItem and dgv gets refreshed.
Problem is the combo box will lose its current selection and goes to unselected state.
I want to retain the selected item even after dgv refreshed.
Could anyone help me out
Thanks in advance
Do you mean that you're using an unbound comboboxcolumn? If so, the value can't automatically be persisted when refreshing the datasource. You need to store the selected value before updating and setting it in code after refresh.
If your column is actually databound, the selected value is either not stored in the database or you have some data type problem.
Is the combobox there to let the user select a value for the field or do you use it as a way to execute a command on the record?
Do you have any code you can post?
Datagrid Combo-Box value will retain the string value but will refresh any integer values automatically.
Here is what you need to do :
-When populating Combo-Box value to just convert its value to toString().
-Also if you are setting a default select value also set it with string type.
-Your Combo-box will automatically retain the value selected even after refreshing.
:)
have a combobox in ur datagridview. Assign values to it using a bindingsource.
then write an eventhandler for the datagridviews "EditingControlShowing" event.
in that, remove had handler if any exists for the comboboxes Selectedindexchanged event. then add an event handler for the selectedIndexChanged event say "ComboBoxValueChanged"
in that "ComboBoxValueChanged",
DirectCast the sender to System.Windows.Forms.DataGridViewComboBoxEditingControl and get the selected value of it.
Now use it to compute any value you want.
you may wana refer to this
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcomboboxeditingcontrol.aspx

Categories