Link to home
Start Free TrialLog in
Avatar of Larry Rungren
Larry RungrenFlag for United States of America

asked on

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

vb.net  25 samples of code, none work?

I Select several items in textbox1.

I click a btn control to move all selected items to textbox2.
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

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 ?
Avatar of Larry Rungren

ASKER

No I didn't mean textbox, I meant listbox I want to move selected items from lstbox1 to lstboxt2.
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
            ls.Add(s)
            ListBox2.Items.Add(s)
        Next
        For Each s As String In ls
            ListBox1.Items.Remove(s)
        Next

Open in new window

User generated imageand
User generated image
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)})
			LeftSource.Add(p)
		Next
		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())
					LeftSource.Add(p)
					RightSource.Remove(p)
				Next
			ElseIf btn.Equals(btnRight) Then
				For Each p As Person In (From element As Person In lbLeft.SelectedItems.OfType(Of Person).Reverse())
					RightSource.Add(p)
					LeftSource.Remove(p)
				Next
			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)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        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.SuspendLayout()
		'
		'lbLeft
		'
		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
		'
		'lbRight
		'
		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
		'
		'btnLeft
		'
		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
		'
		'btnRight
		'
		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
		'
		'Form1
		'
		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.Controls.Add(Me.btnLeft)
		Me.Controls.Add(Me.btnRight)
		Me.Controls.Add(Me.lbRight)
		Me.Controls.Add(Me.lbLeft)
		Me.Name = "Form1"
		Me.Text = "Form1"
		CType(Me.LeftBinder, System.ComponentModel.ISupportInitialize).EndInit()
		CType(Me.RightBinder, System.ComponentModel.ISupportInitialize).EndInit()
		Me.ResumeLayout(False)

	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 -User generated imageUser generated imageUser generated imageIf 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.

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

-saige-
Andy

This is what I get with sample?
errorcapture.jpg
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
     ls.Add(item)
     lstSelSem.Items.Add(item)
Next

Open in new window


-saige-
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.
Sorry guys each option simply throws another error.  How can something so simple get this screwed up?
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.
Don't bind a datasource to that listbox.
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"
ASKER CERTIFIED SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.