move items to the another listbox which is searched by textbox - vb.net

I am beginner at programming. I'm trying to build a form based app using visual basic according to a example in youtube.
In the form I cant move a item from listbox1 to listbox2 which was searched in textbox2
When I write the first item which is placed in first row of listbox1 it moves item to listbox2 but if I try with another item it cant move to listbox2.
I would be happy if someone can help me about this case.
Here are a picture of my form and the code I use :

a Lot depends on what you are putting into the listboxes. If it is simple stuff like a, b, c, d etc it will add everything to listbox 2 as you have your code under text_changed event. Try and use a button when user stopped typing to search for the entire word.
Also add your text after the sc Call to your sc sub before the return statement as well -
Sub sc()
''Current code
''If Textbox2<text - remove, already called...
Listbox2.Items.Add(Listbox1.Text)
Listbox1.Items.Remove(Listbox1.SelectedIndex)
Return
End Sub

Related

Getting Selected Items from a Listbox

Good Wednesday All.
I am running into a brick wall (easy for a shade tree coder to do) I have a Listbox that i populated with a datatable. I want to get the all LicenseID's from the selected items. In other words, if the user selects 3 out of 8 of the list box, I need to get the LicenseID for each of those 3.
Below is how I populated the listbox
Using cmd As New OleDbCommand(cmdText, conn)
conn.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader()
dt.Load(reader)
ListBox1License.DataSource = dt
ListBox1License.DisplayMember = "InstitutionTypeAbrev"
ListBox1License.ValueMember = "LicenseID"
End Using
I need to get the selected items from the listbox to use later.
I am thinking of adding the selected Items to an array.
I have searched around STackOverflow for some examples but none seem to work for me.
Any Help Appreciated
I'll show you how to derive the answer for this yourself:
I've set up a form:
Really simple; the listbox is like your listbox. The button is just there to give me an easy way to stop the code and examine what is going on.
I wrote some code to populate some things into my listbox. It's a screenshot because it doesn't matter that you have exactly this code, so you don't need to write this code (hence why I'm making it hard to copy paste):
I've double clicked my button to make a click handler. I haven't written any code, but I have put a breakpoint on the method declaration - see it's red? Click the margin where the dot is, to put breakpoints in your code. When you hit them, the code stops and waits for you to inspect:
I've run my app and clicked my button. The code has stopped and VS has switched to showing me the code, not the app:
I can now point to some variable that is in scope (like ListBox1) and see a tooltip, or I can open the Locals/Autos windows and see variables that are in scope and drill into them:
Expand you ListBox in the Autos/Locals window. It has a lot of properties. Scroll to SelectedItems:
SelectedItems is a collection of things.. We can tell partly because Microsoft is good at naming collections of things with a plural name, and because the inspector says "enumerate the enumerable" .. it means that it is a bunch of things that we can ForEach to look through
Expanding it we see that my selecteditems has only one thing selected (i truly did only have one selected item in my list when I clicked the button)
We can see that an entry in the SelectedItems collection is a DataRowView type of object. We can see that a DataRowView has a Row property that is a DataRow.. This Row is the DataRow in the DataTable to which the list is bound (you set the DataSource to a DataTable; this is a row from that table).
Every time you dig into the tree another level, that's like using either a dot or an indexer in your code. At this level we've gone listbox1.SelectedItems(0).Row..
So from this we can see that we need a code like:
' we will "enumerate the enumerable"
For Each drv as DataRowView in listbox1.SelectedItems
Dim originalRow = drv.Row 'we could do this to get the row...
Dim selectedAnimaId = row("AnimalID") ' ..and then index the row to get the animal ID ..
Dim selectedAnimalId = drv("AnimalID") ' ... or it's actually possible to index a DataRowView directly, so you can skip the row part
Next drv
It can be handy to write code while you're stopped on a breakpoint so you can look at the values of things as you're writing, and check you're going in the right direction. You might need to use F10 (or whatever key is associated with "step over"/"step into") to move the yellow bar along and execute code lines one by one:
You can only move the code execution along if you've written complete, legal code, but it doesn't have to be logically correct. You can back up and execute again by dragging the yellow arrow in the margin (or right clicking and choosing Set Next Statement). Here I've put some dummy statement in to move along to, so i can check that my animalID is correctly set in X like I expect . I point to X to see the value:
The standard ListBox won't help you with that, past getting the DataRowView objects from the SelectedItems collection. As an alternative, here's a custom control that you can use in place of a standard ListBox that will help you:
Public Class ListBoxEx
Inherits ListBox
Public Function GetItemValue(item As Object) As Object
Dim index = Me.Items.IndexOf(item)
If (index <> -1 AndAlso Me.DataManager IsNot Nothing) Then
Return Me.FilterItemOnProperty(Me.DataManager.List(index), Me.ValueMember)
End If
Return Nothing
End Function
End Class
You can then call GetItemValue and pass any item and get the same value back as you would if that was the SelectedItem and you got the SelectedValue. To get all the values in an array:
Dim licenseIDs = myListBoxEx.SelectedItems.
Cast(Of Object)().
Select(Function(o) CInt(myListBoxEx.GetItemValue(o)).
ToArray()
For more information, see here.
In case you're unaware, if you add a class to your project and it is a control or component, once you build, it will appear automatically at the top of the Toolbox window.
If you already have a standard ListBox in place and you don't want to have to delete it and add a new control, you can edit the designer code file by hand to change the existing control. To do that, open the Solution Explorer and select a node within your project, click the Show All Files button, expand the node for your form, double-click the designer code file and then replace ListBox with ListBoxEx (or whatever you call it) in the relevant places. I'd advise creating a backup copy or syncing with source control first, in case you mess it up.

Fill in a text box when selecting a combo box option on Access

Im not very advanced in Access and I am struggling with defining the VBA code/expression build/ or Control Source for an instruction that can make the following isntruction:
If i make a selection on a Combo box (with my key field "TypeService" on my table TblMain)
Then; my text box is able to return the TypeConfig rows related to the TypeService selected before (my table TblConfig contains TypeServiceFK and TypeConfig fields)
So, my objective is to get a dynamic textbox that depends of a multi option combobox.-
Thanks for the help!!
Put a listbox on your form, let's say it's called List2, and cancel the wizard if it pops up.
In the Row Source property of the listbox, put this SQL statement
SELECT tblConfig.TypeConfig FROM tblConfig WHERE (((tblConfig.TypeService)=[Forms]![frmMain]![Combo0]));
This assumes your form is called frmMain and your combobox is called Combo0, so change those as necessary.
Right click on Combo0 and choose Build Event, then Code Builder. Replace the Sub...End Sub stub with
Private Sub Combo0_Change()
Me.List2.Requery
End Sub
Now every time Combo0 changes, the SQL statement behind List2 will run and return the TypeConfigs associated with that TypeService.

Excel Userform Textbox Constant Set Focus

First of all I would like to thank all of you guys. Maybe you did not notice but you help me to grasp VBA to some level from scratch. I am still in learning process so I may be missing something really simple, please be gentle :)
First of all I would like to give a small backgroud update about my issue. I have been writing a small program to scan incoming parts to my work to be able to keep inventory status. Latest look of the program is like below:
And numbers on the picture are my nightmares lately:
1. Scanned Part Number: This is the textbox where scanner inputs the value. After I receive the input I immidietly convert that data to a variable and clear the textbox value as below:
Private Sub PN_CurrentScan_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then
EnteredPN = Replace(PN_CurrentScan.Value, Chr(32), "", 1) '<---PN_CurrentScan is the name of text box
EnteredPN = Left(EnteredPN, 12)
PN_CurrentScan.Value = ""
After making some corrections on the scanned data I basically write it to a sheet in the workbook. Then I also have a pivot table in the same workbook which uses this scanned data as source and counts how many parts scanned from each part number.
2. Current Status: This ListBox contains all the part numbers scanned (Coming from the pivot table mentioned above) and waiting to be scanned (Coming from another worksheet). Then it refreshes it self every time a new part is scanned.
3. ListBox Scroll Bar: Since I have very long part number list it is not possible for me to fit everything on the screen that is why listbox creates this scroll bar.
Enough with the background I think :)
So if we come to my concern. Since my collages using cordless scanner to do this operation sometimes they don't have the chance to see the screen so they can not understand if the cursor is on the "Scanned Part Number Text Box" or not. That is why I need focus to be on that box no matter what happens (Of course we can not do anything if warehouse burns down, earth quake or tsunami hits the place but let do not think about those).
WHAT I HAVE TRIED:
First of all I disabled all the remaining objects from properties window
Then I diabled tab stops of all controls:
Dim contr As Control
For Each contr In ScannerInterface.Controls
On Error Resume Next
contr.TabStop = False
Next
ScannerInterface.PN_CurrentScan.TabStop = True
Added setfocus property to all button clicks:
Me.PN_CurrentScan.SetFocus
Added setfocus property to listbox click:
Private Sub CurrentStatus_List_Click()
Me.PN_CurrentScan.SetFocus
End Sub
Added set focus to enter and exit events of listbox however this did not work:
Private Sub CurrentStatus_List_Enter()
Me.PN_CurrentScan.SetFocus
End Sub
Private Sub CurrentStatus_List_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Me.PN_CurrentScan.SetFocus
End Sub
So, with all these counter measures I have managed to improve up to somepoint, only concern remaining is when I click on the scroll bar next to the listbox, text box lose focus and without clicking in the textbox I could not manage to set the focus again. I tried all events with listbox non of them worked. Is there any way to solve this problem or do I need to deal with this? Thanks in advance for your supports.
SOLUTION:
Thanks to #Rory we have managed to solve my problem. As he noticed and explained in the answer below, both my textbox and listbox were in frames. I have tried several setfocus options but I always gave the focus to the textbox. However, solution was to give the focus to the frame which was containing the target textbox:
Private Sub CurrentStatus_Frame_Enter() '<-- Enter event of the frame which contains listbox
Me.PN_CurrentScan.SetFocus '<-- Setfocus to target textbox
Me.Scanned_Frame.SetFocus '<-- Setfocus to frame which contains target textbox
End Sub
Having (eventually) noticed that both of your controls are inside container Frame controls, you can actually use the Enter event of the Frame that contains the listbox to set focus to the Frame that contains the textbox, rather than to the textbox itself.

Visual Basic: How to replace selected NumericUpDowns with ComboBoxes

Is it possible to replace the selected NumericUpDown controls with ComboBoxes?
I understand that not all properties can be conserved but the only properties I need are the location and the size.
The workflow I have in mind is as follows:
Select certain NumericUpDowns
Click replace with... and then select ComboBoxes (or any other approach)
Where the NumericUpDowns were, there are now ComboBoxes of the same size
The reason I want to do this is that I have to put together a GUI with multiple tabs. Each tab page has a list of Labels with either NumericUpDowns or ControlBoxes next to it. The order of the controls changes per tab. I just want to copy the items on the first tab and paste them on the other tabs. Then per tab I only have to change certain NumericUpDowns into ComboBoxes.
I started with VB yesterday so I might be overlooking something.
The quickest is doing it manually, we cant change your GUI remotely - since you are at an entry level with a language you do not know well, RAD is the best recommendation - this way you can study what it does - just like learning HTML with DreamWeaver's RAD tools.
Since your interested, (I know your new to VB so I'dd make it heaps clear) you do these steps:
a) Open Winforms VS 2008 solution
b) Click the File > Create New Project > WinForms
c) Double click the form and it will show you the forms code
d) Then in the constructor method you will see the line InitializeComponent
e) Right Click on this method call and chose Goto Definition
f) This will show you the code that populates the form with controls
g) Then for each form I'm suggestion you replace all the NumericUpDown's with ComboBoxes in the xyz.Designer.vb file
However I'd really recommend doing it with Visual Studio IDE. Don't be frightened.
Private sub Replace_By_ComboBox(ByVal nud As NumericUpDowns)
'Create new combo box
Dim cbx As New ComboBox
cbx.Left = nud.Left
cbx.To = nud.Top
cbx.Width = nud.Width
cbx.Height = nud.Height
cbx.Visible = True
cbx.Enabled = True
'Add the combo box
nud.Parent.Controls.Add(cbx)
'Remove the NumericUpDowns
nud.Parent.Controls.Remove(nud)
End Sub

Allowing user to select text in word vba macro

In VBA for Word 2007, I want to be able to open a document, highlight sections of text and replace those sections with fields linked to a docvariables. The process would be:
Open document.
Select text.
Select docvariable from list.
Insert field linked to selected docvariable.
Repeat steps 1-4 as required.
There is no way to know beforehand what the text to be selected is or which docvariable is going to be linked to which field or how many times these steps are going to be repeated.
Only with Microsoft could the most absolutely fundamental, simple task of allowing the user to make a selection at run-time and pass this selection back to sub-routine be so tortuous and surreal. I have spent 2 days trying to figure this out. If anyone can help, I will name my next child after you.
I think "tortuous and surreal" is a misconception.
Create a small form with a dropdown (named "selVarName", for example) that lets you select all document variable names available. Link the form to a custom button in the Quick Access Toolbar.
Upon clicking "OK" in this form do something like this:
Private Sub btnOK_Click()
Dim v As Word.Variable
Dim n As String
n = Me.selVarName.Value
With Selection
For Each v In .Document.Variables
If v.Name = n Then v.Delete: Exit For
Next v
.Document.Variables.Add n, .Range.Text
End With
End Sub
And this has bells and whistles already. You can do additional checking like "no text selected", for example.