Multi select listbox's last clicked item to textbox - vb.net

I want to show the last clicked item on my ListBox that has multi-select. It only shows the first item on the list selected when I use the following:
Textbox1.text = listbox1.text

I think your only option would be to store a list of the selected indices and add/remove to/from it whenever the selection changes.
Something like this should do the job (assuming WinForms):
Private selectedIndices As New List(Of Integer)
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
' Add the newly selected items.
selectedIndices.AddRange(
ListBox1.SelectedIndices.Cast(Of Integer).
Where(Function(i) Not selectedIndices.Contains(i)))
' Remove the unselected items.
selectedIndices.RemoveAll(Function(i) Not ListBox1.SelectedIndices.Contains(i))
' Update the TextBox text. You can move this code to a different method
' if you want to trigger it using a button or something.
If selectedIndices.Count = 0 Then
TextBox1.Text = String.Empty
Else
Dim lastIndex As Integer = selectedIndices.Last()
TextBox1.Text = ListBox1.GetItemText(ListBox1.Items(lastIndex))
End If
End Sub
See it in action:

Related

How to get item text from CheckedListBox to ListBox without repeating the before text? VB.net

I have a CheckedListBox of 10 names A to J (it's a string but here I'm just using abc), and I want to make it so that every time a user check something, the text will be shown in the listbox simultaneously. I have tried this:
For i = 0 To chklistbxDrugAvailableList.Items.Count - 1
Dim drugs As String = CType(chklistbxDrugAvailableList.Items(i), String)
If chklistbxDrugAvailableList.GetItemChecked(i) Then
listbxYourOrder.Items.Add(drugs)
End If
'drugs = nothing
Next
But when I check A,B,C the text in the Listbox got repeated like so:
A
A
B
A
B
C
I don't know why this is happening. I didn't declare drugs as an array. Even when I used the drugs = nothing, it still give repeated values.
What should I do? Sorry if this is a noob question.
Here is how I would do the whole thing:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
'Clear the current ListBox contents.
ListBox1.Items.Clear()
'Get the indexes of the currently checked items.
Dim checkedIndices = CheckedListBox1.CheckedIndices.Cast(Of Integer)()
'Add the current index to the list if the item is being checked, otherwise remove it.
checkedIndices = If(e.NewValue = CheckState.Checked,
checkedIndices.Append(e.Index),
checkedIndices.Except({e.Index}))
'Get the checked items in order and add them to the ListBox.
ListBox1.Items.AddRange(checkedIndices.OrderBy(Function(n) n).
Select(Function(i) CheckedListBox1.Items(i)).
ToArray())
End Sub
or like this:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
'Get the indexes of the currently checked items.
Dim checkedIndices = CheckedListBox1.CheckedIndices.Cast(Of Integer)()
'Add the current index to the list if the item is being checked, otherwise remove it.
checkedIndices = If(e.NewValue = CheckState.Checked,
checkedIndices.Append(e.Index),
checkedIndices.Except({e.Index}))
'Get the checked items in order and add them to the ListBox.
ListBox1.DataSource = checkedIndices.OrderBy(Function(n) n).
Select(Function(i) CheckedListBox1.Items(i)).
ToArray()
End Sub
The difference is that, because the second option uses data-binding, the first item in the ListBox will be selected by default.
The reason that it needs to be a bit verbose is that the ItemCheck event is raised before the item is checked or unchecked. For that reason, we need to get the currently checked items first and then either add or remove the current item, depending on whether the current item is being checked or unchecked.
EDIT:
Here's an option that doesn't require clearing the ListBox:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
Dim item = CheckedListBox1.Items(e.Index)
If e.NewValue = CheckState.Checked Then
ListBox1.Items.Add(item)
Else
ListBox1.Items.Remove(item)
End If
End Sub
The issue with that is that the items will appear in the ListBox in the order you checked them, rather than the order they appear in the CheckedListBox. The other options keep the items in the same order in both lists.
If I understand your question I would this:
lstbxYourOrder.Items.Clear()
For Each l As String In chklistbxDrugAvailableList.CheckedItems
listbxYourOrder.Items.Add(l)
Next

Trying to make smart combobox item interaction

I am here to find out is it possible to complete my idea to save me time writing long code.
I have 1 main combobox with various items and some other comboboxed. Each combobox of them is called "Combo" + the item from the main combobox.
and I wonder can I, when I click on an item to hide the last used combobox and to show the combobox linked to this item?
1. hide last used combobox
2. show the combobox responding to the selected item from the main combox
Public Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
Dim SelectedAction As String = "Combo" + ComboBox2.Text
lastcombobox.visible = false
' now to assign to the new combobox
lastcombobox = (SelectedAction as name of combobox) combobox
Lastcombobox.visible = true
End Sub
Strings are not controls. Strings are the data type of Control.Name; that is the Name property of the control object. You cannot cast a string to a control but all is not lost. Create your other Combo Boxes at design time and stack them on top of each other. Notice the Static keyword before lastComboBox. This persists the value between calls to the method. You could accomplish the same thing by making this variable a class level variable. The first time the method is called their will be nothing in lastComboBox therefore the check for IsNothhing. Control.Find returns an array so we must refer to ctl(0) - the first element of the array, since we know it will return only one.
Private Sub Combo2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Combo2.SelectedIndexChanged
Dim SelectedAction As String = "Combo" & Combo2.Text
Static lastComboBox As ComboBox
If Not IsNothing(lastComboBox) Then
lastComboBox.Visible = False
End If
Dim ctl() As Control = Controls.Find(SelectedAction, True)
lastComboBox = CType(ctl(0), ComboBox)
lastComboBox.BringToFront()
lastComboBox.Visible = True
End Sub

Delete line of structure array and update it in tab vb.net

So I have a listbox, filled with informations from a structure tab as follows :
Private Sub Modifier_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 0 To frmConnecter.TabPolyFlix.Length - 1
ListBox1.Items.Add(frmConnecter.TabPolyFlix(i).strTitre)
Next
End Sub
And I want the user to choose to delete the TabPolyFlix(ListBox1.SelectedIndex) and it has to get updated in the original Tab and thus in the Listbox
P.S I tried this but it only updates it in the listbox, not in the original tab
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Temp As New List(Of ListViewItem)
For i As Integer = 0 To ListBox1.Items.Count - 1
If ListBox1.SelectedIndices.Contains(i) = False Then
Temp.Add(ListBox1.Items(i))
End If
Next
ListBox1.Items.Clear()
For i As Integer = 0 To Temp.Count - 1
ListBox1.Items.Add(Temp(i))
Next i
End Sub
Arrays have a fixed size. Better use a List(Of ListViewItem) for TabPolyFlix. Then assign the List directly to the DataSource of the listbox:
'Fill the listbox
ListBox1.DisplayMember = "strTitre" 'You can also set this in the property grid.
ListBox1.DataSource = frmConnecter.TabPolyFlix
You can also override the ToString method of ListViewItem in order to display anything you want in the listbox and keep ListBox1.DisplayMember empty.
Now you can directly delete the item in the list:
frmConnecter.TabPolyFlix.Remove(ListBox1.SelectedItem)
or
frmConnecter.TabPolyFlix.RemoveAt(ListBox1.SelectedIndex)
or if you want to delete several items at once
For Each i As Integer In ListBox1.SelectedIndices.Cast(Of Integer)()
frmConnecter.TabPolyFlix.Remove(ListBox1.Items(i))
Next
and re-display the list:
ListBox1.DataSource = Nothing
ListBox1.DataSource = frmConnecter.TabPolyFlix
The moral of the story is: don't use controls (the ListBox in this case) as your primary data structure. Use it only for display and user interaction. Perform the logic (the so called business logic) on display-independent data structures and objects (so called business objects) and when finished, display the result.

VB.NET ComboBox results selected item

Hi I have a vb windows form application that has a ComboBox from the form1 I have some code that reads some registry and adds item results to combobox. I would like to select one of the results and run a start process. My problem is where do I put the code when item is selected then do something and how to I determine what has been selected?
My Code to query registry keys
Dim Key, Reader As RegistryKey, Y As String
Key = Registry.LocalMachine.OpenSubKey("SOFTWARE\AppStream\AppMgr\Shortcuts", False)
For Each X In Key.GetSubKeyNames
Reader = Registry.LocalMachine.OpenSubKey("SOFTWARE\AppStream\AppMgr\Shortcuts\" & X, False)
If Reader.GetValueNames().Contains("AppTitle") Then
Y = Reader.GetValue("AppTitle")
If Not ComboBox1.Items.Contains(Y) Then ComboBox1.Items.Add(Y)
End If
If i do somehting like this, it just shows a blank messagebox and I have not selected that text from combobox yet.
If ComboBox1.SelectedText Then
MessageBox.Show(ComboBox1.SelectedText())
End If
You subscribe to the SelectedIndexChanged event writing a method like this
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim comboBox As comboBox = CType(sender, comboBox)
' Caution, the event could be called also when there is nothing selected
if combBox.SelectedItem IsNot Nothing Then
Dim curValue = CType(combBox.SelectedItem, String)
'do your stuff with the selected key'
End If
End Sub
if combBox.SelectedItem IsNot Nothing Then
Dim cmbselected As String = DirectCast(DirectCast(DirectCast(DirectCast(combBox, System.Windows.Controls.ComboBox).SelectedValue, System.Object), System.Data.DataRowView).Row, System.Data.DataRow).ItemArray(0)
End If

How to adding checked item from checkedlistbox to combobox

I want to adding checked item from checkedlistbox to my combobox, but i have a little problem here. Combobox only show 1 item last checked.
This is my sample code.
If CheckedListBox1.CheckedItems.Count <> 0 Then
For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
cbCheckedItem.Text = CheckedListBox1.CheckedItems(i).ToString
Next i
End If
anyone can help me show all checked item??
thank's for your help...
You aren't adding the items to the combo box, you're only setting its Text property. That's only changing the text currently displayed in the combo box, and only one item can be displayed at a time.
If you want the items to be permanent and selectable, you need to add them to the combo box control's Items collection.
Sample code:
If CheckedListBox1.CheckedItems.Count > 0 Then
For Each checkedItem In CheckedListBox1.CheckedItems
cbCheckedItem.Items.Add(checkedItem.ToString())
Next
End If
Or, better yet, use the AddRange method:
If CheckedListBox1.CheckedItems.Count > 0 Then
Dim checkedItems() As String = CheckedListBox1.CheckedItems.Cast(Of String).ToArray()
cbCheckedItems.Items.AddRange(checkedItems)
End If
Oddly enough the CheckedListBox has a CheckedItems property, which is a collection. As such you can loop through it like you can any other collection, using a For or For Each loop.
then, Each item needs to be added to the Items collection of the ComboBox.
like this sample:
Public Class frmCheckedListBox
Private Sub frmCheckedListBox_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CheckedListBox1.Items.Clear()
Me.CheckedListBox1.BeginUpdate()
Me.CheckedListBox1.Items.Add("One")
Me.CheckedListBox1.Items.Add("Two")
Me.CheckedListBox1.Items.Add("Three")
Me.CheckedListBox1.Items.Add("Four")
Me.CheckedListBox1.Items.Add("Five")
Me.CheckedListBox1.EndUpdate()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each Item As String In Me.CheckedListBox1.CheckedItems
Me.ComboBox1.Items.Add(Item)
Me.ComboBox1.SelectedIndex = 0
Next
End Sub
End Class
As sample code shows, the CheckedItems collection contains the items that are checked, just as the name suggests. It doesn't contain a Boolean value for each an every item to indicate whether it is checked or not. If an item is checked then that item is in the CheckedItems, and if it isn't then it isn't. You simply need to loop through the collection and get every item in it, because it contains all the items that are checked and none that aren't.
in the end you can put :
Me.Combobox1.items.clear()
because when it would click with sample code it would have the one that clicked then on the next click would return the previous one it had clicked and then the new one all compiled in the combobox selection menu
perhaps my answer can help you solve your problems
Combobox doesn't have a multiselect option. so only one item at a time could be selected.