moving selected Items from one text box to another

I have searched the web for vb2010 code detailing how to move selected items in one text box to another.

VB6 4 lines of code  25 samples of code, none work?

I Select several items in textbox1.

I click a btn control to move all selected items to textbox2.
Larry RungrenDirector of TechnologyAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
I have a feeling you are talking about Textbox but actually meaning Listbox.  (One doesn't usually have items in a Textbox).   Code for one type of object won't work when confronted with the other type (maybe why your example code you found isn't working).

Do you really mean Textbox or is it a Listbox ?
Larry RungrenDirector of TechnologyAuthor Commented:
No I didn't mean textbox, I meant listbox I want to move selected items from lstbox1 to lstboxt2.
AndyAinscowFreelance programmer / ConsultantCommented:
This will work.  (You can probably optimise it but this shows the principles involved).
        Dim ls As List(Of String) = New List(Of String)
        For Each s As String In ListBox1.SelectedItems
        For Each s As String In ls

Open in new window

Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Perhaps you meant from a listbox to a listbox.  A textbox control does not have a concept of items as it's value is really just a string (single- or multi-lined).

However, there are plenty of ways to do this using Listbox's.  Here is one way that I prefer:

Form1.vb -
Imports System.ComponentModel
Imports System.Linq

Public Class Form1
	ReadOnly LeftSource As New BindingList(Of Person)
	ReadOnly RightSource As New BindingList(Of Person)

	Private Sub OnLoad(sender As Object, e As EventArgs) Handles MyBase.Load
		For Each p As Person In (From i As Integer In Enumerable.Range(0, 20) Select New Person() With {.ID = i, .FirstName = String.Format("First{0}", i), .LastName = String.Format("Last{0}", i)})
		LeftBinder.DataSource = LeftSource
		RightBinder.DataSource = RightSource
		lbLeft.DataSource = LeftBinder
		lbRight.DataSource = RightBinder
	End Sub

	Private Sub OnClick(sender As Object, e As EventArgs) Handles btnRight.Click, btnLeft.Click
		If TypeOf sender Is Button Then
			Dim btn As Button = DirectCast(sender, Button)
			If btn.Equals(btnLeft) Then
				For Each p As Person In (From element As Person In lbRight.SelectedItems.OfType(Of Person).Reverse())
			ElseIf btn.Equals(btnRight) Then
				For Each p As Person In (From element As Person In lbLeft.SelectedItems.OfType(Of Person).Reverse())
			End If
		End If
	End Sub

	Private Sub OnSelectedValueChanged(sender As Object, e As EventArgs) Handles lbRight.SelectedValueChanged, lbLeft.SelectedValueChanged
		If TypeOf sender Is ListBox Then
			Dim lb As ListBox = DirectCast(sender, ListBox)
			If lb.Equals(lbLeft) Then
				btnRight.Enabled = lb.SelectedItems.Count > 0
			ElseIf lb.Equals(lbRight) Then
				btnLeft.Enabled = lb.SelectedItems.Count > 0
			End If
		End If
	End Sub
End Class

Class Person
	Public Property ID() As Integer
	Public Property FirstName() As String
	Public Property LastName() As String

	Public Overrides Function ToString() As String
		Return String.Format("{0}, {1} [{2}]", LastName, FirstName, ID)
	End Function
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing AndAlso components IsNot Nothing Then
            End If
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.components = New System.ComponentModel.Container()
		Me.lbLeft = New System.Windows.Forms.ListBox()
		Me.lbRight = New System.Windows.Forms.ListBox()
		Me.btnLeft = New System.Windows.Forms.Button()
		Me.btnRight = New System.Windows.Forms.Button()
		Me.LeftBinder = New System.Windows.Forms.BindingSource(Me.components)
		Me.RightBinder = New System.Windows.Forms.BindingSource(Me.components)
		CType(Me.LeftBinder, System.ComponentModel.ISupportInitialize).BeginInit()
		CType(Me.RightBinder, System.ComponentModel.ISupportInitialize).BeginInit()
		Me.lbLeft.FormattingEnabled = True
		Me.lbLeft.Location = New System.Drawing.Point(12, 16)
		Me.lbLeft.Name = "lbLeft"
		Me.lbLeft.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended
		Me.lbLeft.Size = New System.Drawing.Size(202, 290)
		Me.lbLeft.TabIndex = 0
		Me.lbRight.FormattingEnabled = True
		Me.lbRight.Location = New System.Drawing.Point(342, 16)
		Me.lbRight.Name = "lbRight"
		Me.lbRight.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended
		Me.lbRight.Size = New System.Drawing.Size(202, 290)
		Me.lbRight.TabIndex = 1
		Me.btnLeft.Location = New System.Drawing.Point(221, 162)
		Me.btnLeft.Name = "btnLeft"
		Me.btnLeft.Size = New System.Drawing.Size(115, 23)
		Me.btnLeft.TabIndex = 5
		Me.btnLeft.Text = "<<"
		Me.btnLeft.UseVisualStyleBackColor = True
		Me.btnRight.Location = New System.Drawing.Point(221, 133)
		Me.btnRight.Name = "btnRight"
		Me.btnRight.Size = New System.Drawing.Size(115, 23)
		Me.btnRight.TabIndex = 4
		Me.btnRight.Text = ">>"
		Me.btnRight.UseVisualStyleBackColor = True
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(556, 318)
		Me.Name = "Form1"
		Me.Text = "Form1"
		CType(Me.LeftBinder, System.ComponentModel.ISupportInitialize).EndInit()
		CType(Me.RightBinder, System.ComponentModel.ISupportInitialize).EndInit()

	End Sub
	Friend WithEvents lbLeft As System.Windows.Forms.ListBox
	Friend WithEvents lbRight As System.Windows.Forms.ListBox
	Friend WithEvents btnLeft As System.Windows.Forms.Button
	Friend WithEvents btnRight As System.Windows.Forms.Button
	Friend WithEvents LeftBinder As System.Windows.Forms.BindingSource
	Friend WithEvents RightBinder As System.Windows.Forms.BindingSource

End Class

Open in new window

Which produces the following output -Initial load.Here we choose some items.We click the right arrow button to move the items from one list box to the other.If you implement this, you will see that it works both ways.

As a rule, I wouldn't get caught up on the line differences between VB6 and VB.NET.  As a whole you will find that many algorithmic functions are simpler to implement in VB.NET than in VB6.

Or I could be late to the party and find that Andy has provided a sufficient answer.  ;)

Larry RungrenDirector of TechnologyAuthor Commented:

This is what I get with sample?
Larry RungrenDirector of TechnologyAuthor Commented:
it_sage code compiles but errors out, see my last post

Thanks you guys, I need to get the item off my plate.
The problem is easily resolved.  You are trying to move DataRowView objects.  To do this, you must change the DataType of the List; e.g. -
Dim ls As List(Of DataRowView) = New List(Of DataRowView)
For Each item As DataRowView In lstAllSem.SelectedItems

Open in new window

AndyAinscowFreelance programmer / ConsultantCommented:
Try my example with a Listbox containing strings.  It does work because the Listbox contains strings and the code specifically uses strings as the type of object being transferred.

Now make the change suggested by it_saige in the previous comment in your real world app and it will hopefully work.  I say hopefully because I dont know just what the DataRowView is.
Larry RungrenDirector of TechnologyAuthor Commented:
Sorry guys each option simply throws another error.  How can something so simple get this screwed up?
AndyAinscowFreelance programmer / ConsultantCommented:
Did you try my suggestion of a simple app with just a few strings in the listbox.
It WILL work.  That shows you the principle is functional.

ps.  If you are binding a datasource then you have to manipulate the underlying datasource not the items in the listbox.
Larry RungrenDirector of TechnologyAuthor Commented:
AndyAinscowFreelance programmer / ConsultantCommented:
Don't bind a datasource to that listbox.
Larry RungrenDirector of TechnologyAuthor Commented:
Thers is no databinding set for either textbox. there are items in textbox2 that may have been selected previously.  Once selected rows are written to a table and if the user wants to edit the selected list they can add items from lstallsem or delete from lstselsem does the initial load of info from table mean that the lstselsem is "bound"
AndyAinscowFreelance programmer / ConsultantCommented:
If the DataSource is set via the properties (or via code) then it is bound.  As I said earlier if you use bound ListBoxs then you have to modify the data source not the item collection as in my example.  The principle is the same.  SNAG-0007.bmp

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Larry RungrenDirector of TechnologyAuthor Commented:
I understand the theory of what you are saying.  The list box when populated was done using a datasource setting to a dataset.

I could find no wayt to drop the dataset or datasource, so I now write the selected records from lstall to the table and repopulate the list box.
I realize is is probably not the best way but I can't spend anymore time attempting to decipher why something this simple has to be so convoluted.  I appreciate your assistance, and I will, on the next application that has to be converted,  use the datareader to populate forms and sql commands to update tables.  It certainly does appear to be the better method for desktop applications.

Again thanks for putting up with a frustrated newbie.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.