How to remove list from textbox after removing the last list of list collection - vb.net

I have a windows application which input string to be insert into list of collections. Then, displays it in a text box field(Multiple lines). The problem I'm having now is the list is still there in the textbox after I clicked 'Delete button', but the last index is successfully deleted. How can I automatically delete the list in the textbox as well as the list of collection itself? it that possible to do?
These are the code snippet that I have done.
Public strList As List(Of String) = New List(Of String)
'add string to list
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TxtBox.Text <> "" Then
strList.Add(TxtBox.Text)
TxtBox.Clear()
End If
txtList.Clear()
For Each s As String In strList
txtList.Text += s & Environment.NewLine & Environment.NewLine
Next
End Sub
'delete Button
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
strList.RemoveAt(strList.Count - 1)
End Sub
Thanks in advance!

Have you tried using
strList.Clear() ?
It's not possible to clear the TxtBox automatically, since it's not bind with the list, you just added the text to the textbox, try to use datasource and listView and bind them together if you want to achieve this.
Thanks
Edited:
In case you want to remove last line from the textbox,
You have to rebuilt the string after you remove your last item from the list, the method will be something like this
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
strList.RemoveAt(strList.Count - 1)
txtList.Clear()
For Each s As String In strList
txtList.Text += s & Environment.NewLine & Environment.NewLine
Next
End Sub
Also i prefer to use another control for managing your list, like ListView
VB Listview Basics

Related

How to transfer data from listbox to textbox in Visual Basic

I did some activity but I cant figure out how to retrieve data from listbox1 to textbox1. Example in the listbox1 there are 4 names: John, Jorge, Joe. Then I want to transfer Joe from listbox1 to textbox1. I did an arraylist where I adding those 3 names in the listbox1 but I didn't know how to retrieve the name "Jorge" from listbox1 to textbox1. Send help.
Here's the code where I try to retrieve one of the name from listbox1 to textbox1
Private Sub Retrievebtn_Click(sender As Object, e As EventArgs) Handles Retrievebtn.Click
If textbox1.Text = ListBox1.Items.Count Then
textbox1.Text = ArrayofNames(x)
End If
End Sub
Here's the whole code
Public Class Form1
Dim ArrayofNames() As String
Dim x As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Retrievebtn_Click(sender As Object, e As EventArgs) Handles Retrievebtn.Click
If textbox1.Text = ListBox1.Items.Count Then
textbox1.Text = ArrayofNames(x)
End If
End Sub
Private Sub Addbtn_Click(sender As Object, e As EventArgs) Handles Addbtn.Click
Dim x As Integer = 0
ReDim ArrayofNames(x)
For x = 0 To ArrayofNames.Length - 1
ArrayofNames(x) = Addtextbox.Text
ListBox1.Items.Add(ArrayofNames(x))
Next
End Sub
Private Sub removeBtn_Click(sender As Object, e As EventArgs) Handles removeBtn.Click
ListBox1.Items.Remove(ListBox1.SelectedItem)
End Sub
End Class
Here's the Image of the interface i try to retrieve the name Joe but it wasn'tshowing
Let's go over the code you posted.
In the retrieve button click event you are comparing and Integer to a String with textbox1.Text = ListBox1.Items.Count This won't compile with Option Strict On. You do have Option Strict On, don't you? You should always have this on.
On the next line, you assign the value of ArrayofNames(x), where x refers to your form level variable, to a text box's Text property. Since the value of x is never changed anywhere in the code this will always return the 0 index in the array. (The first element) I can't imagine why it should matter that the Textbox.Text should equal the count of the ListBox items.
In the add button click event you first declare a local variable x. Any code in the method will use this x, not the form level x. You ReDim (without the Preserve keyword) the array to an array with a single element. Your For loop is silly because the length of ArrayofNames is 1, so it is 0 To 0.
The ArrayofNames will never have more than a single element and it will be overwritten each time the add button is clicked.
Fortunately the Listbox maintains its own collection of items.
We can use this collection to simplify your code. Just add the contents of the text box to the the list items.
To retrieve a value from the list box you must first determine if the user has entered a valid index. First, is the entry a valid Integer and is it an index present in the list box.
Remember that .net collections start at index 0.
I use default names in my test program but you should continue to use meaningful names for your controls.
'Your add button
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim index As Integer
If Integer.TryParse(TextBox1.Text, index) AndAlso index >= 0 AndAlso ListBox1.Items.Count - 1 >= index Then
TextBox2.Text = ListBox1.Items(index).ToString
End If
End Sub
'Your add button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
ListBox1.Items.Add(TextBox3.Text)
End Sub

Try to read text , put on list , then compare on list and finally replace txt file

Trying to read a .txt file , put items to list, then on textbox change compare if the string exists in the list. Finally write the new list on the same .txt file.
Public Class Form1
Dim stockList As New List(Of String)
private sub
ListBox1.Items.AddRange(IO.File.ReadAllLines("C:\Users\path\file.txt"))
end sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles
TextBox1.ReadOnlyChanged
Dim text As String = TextBox1.Text
If TextBox1.Text <> "TRAINING" Then
For Each item As Object In ListBox1.Items
If item.ToString = text Then
MsgBox("This code has already been used.", 0, "cheat attempt violation") ' Else alert the user that item already exist
Else
ListBox1.Items.Add(TextBox1.Text)
End If
Next
End If
IO.File.WriteAllLines("C:\Users\path\file.txt", ListBox1.Items.Cast(Of String).ToArray)
End Sub
Instead of using a UI control to store data, you should store the data in a variable. I'm not sure if you really need to show the data in a ListBox, so in the following example code I didn't.
If you use a List(Of String) instead of an array of strings, it is simpler to add another item before saving it.
The Contains method I used in the example can take a second parameter which does the comparison of the item - I guessed that you might want to ignore the case (e.g. "ABC" is the same as "aBc") so I used StringComparer.CurrentCultureIgnoreCase.
I suspect that you want to use the Control.Validating Event instead of the TextChanged event. When the data has been validated, the Control.Validated event handler is used to save it.
I put one TextBox and one Button on the form, so that the focus could change away from the TextBox, e.g. when pressing tab, to fire the validating event.
Imports System.IO
Public Class Form1
Dim dataFile As String = "C:\temp\grains.txt"
Dim alreadyUsed As List(Of String) = Nothing
Sub LoadAlreadyUsed(filename As String)
'TODO: Add exception checking, e.g., the file might not exist.
alreadyUsed = File.ReadAllLines(filename).ToList()
End Sub
Sub SaveAlreadyUsed(filename As String)
File.WriteAllLines(dataFile, alreadyUsed)
End Sub
Function CodeIsAlreadyUsed(newCode As String) As Boolean
Return alreadyUsed.Contains(newCode, StringComparer.CurrentCultureIgnoreCase)
End Function
Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
' Do nothing if the user has clicked the form close button
' See https://stackoverflow.com/questions/15920770/closing-the-c-sharp-windows-form-by-avoiding-textbox-validation
If Me.ActiveControl.Equals(sender) Then
Exit Sub
End If
Dim txt = DirectCast(sender, TextBox).Text
If CodeIsAlreadyUsed(txt) Then
MessageBox.Show("This code has already been used.", "Cheat attempt violation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
e.Cancel = True
End If
End Sub
Private Sub TextBox1_Validated(sender As Object, e As EventArgs) Handles TextBox1.Validated
' The Validated event is raised before the FormClosing event.
' We do not want to save the data when the form is closing.
If Me.ActiveControl.Equals(sender) Then
Exit Sub
End If
Dim txt = DirectCast(sender, TextBox).Text
alreadyUsed.Add(txt)
SaveAlreadyUsed(dataFile)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadAlreadyUsed(dataFile)
End Sub
End Class

Suggest Append Count in combobox (vb.net)

I'm searching for a way to count my remaining suggest appends in my combobox.
In my example I have a list of 7 items
When I start to type with the suggest append function, this list gets narrowed down. But I don't see any possibility to count these remaining appends.
What my main objective is, is that I do an action once I have only 1 suggest append remaining.
But I can only check on the selectedindex, which is in this case always -1, or my comboboxcount is still 7. I don't see a way to count the remaining suggest appends.
Any idea?
Supposing that your combobox listitems are of string type then this code will do that. First you should create a list of string with combobox items. Then on keyup event of combobox you should create the searchtext which you use to filter list then count. See code below (i have shown also searchtext just to see its value):
Dim lst As New List(Of String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each it In ComboBox1.Items
lst.Add(it)
Next
End Sub
Private Sub ComboBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyUp
Dim seltext = ComboBox1.SelectedText
Dim searchtext = ""
If seltext <> "" Then
searchtext = ComboBox1.Text.ToLower.Replace(seltext, "")
Else
searchtext = ComboBox1.Text.ToLower
End If
Label1.Text = lst.Where(Function(d) d.ToLower.StartsWith(searchtext)).Count & " - " & searchtext
End Sub
If your combobox listitems are of different object type then you have to populate list with text field of listitem.
I had the same basic idea as Shurki, except I didn't use a list or replace the selected text with a zero-length string.
I use the SelectionStart property of the ComboBox to get a substring from the ComboBox's Text property..
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
ComboBox1.Items.Add("Candy")
ComboBox1.Items.Add("Car")
ComboBox1.Items.Add("Crush")
ComboBox1.Items.Add("Canned")
ComboBox1.Items.Add("Can")
End Sub
Private Sub ComboBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyUp
Dim query As IEnumerable(Of Object) =
From item As Object In ComboBox1.Items
Where item.ToString().ToUpper().StartsWith(ComboBox1.Text.Substring(0, ComboBox1.SelectionStart).ToUpper())
Select item
Debug.WriteLine("Number of items: " & query.Count())
End Sub
End Class

VBNET: How to Reset ComboBox after selection is made

How do I reset a ComboBox to default Text i set in properties. Say I have a ComboBox with default text "Ruby" which when SelectedIndexChanged is printed in TextBox afterwards it does'nt reset to default text "Ruby" but the SelectedItem. I want it to read "Ruby" afterwards or all the time if not possible. Thank you
Declare the helper class variable in the form class:
Dim _originalComboText As String
On opening the form, remember the default text of the control in some helper variable. For example, add the following line into the constructor (Sub New()):
_originalComboText = ComboBox1.Text
Every time after the selection is made, restore the text from it:
ComboBox1.Text = _originalComboText
If you inspect the content of the .designer.vb file belonging to your form, you can actually see initialization of text of your control through the assignment (=) – so vb.net does no special magic here. If you want to preserve the text, you have to save it somewhere before it gets lost.
Here is the complete minimum example:
Public Class Form1
Dim _originalComboText As String
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
_originalComboText = ComboBox1.Text
End Sub
Private Sub ComboBox1_Leave(sender As Object, e As EventArgs) Handles ComboBox1.Leave
ComboBox1.Text = _originalComboText
End Sub
Private Sub ComboBox1_LocationChanged(sender As Object, e As EventArgs) Handles ComboBox1.LocationChanged
ComboBox1.Text = _originalComboText
End Sub
End Class
And if your two handlers do not differ, then replace them just with one – with two events in Handles clause:
Private Sub ComboBox1_RestoreText(sender As Object, e As EventArgs) _
Handles ComboBox1.Leave, ComboBox1.LocationChanged
ComboBox1.Text = _originalComboText
End Sub
Use this:
Private Sub ComboBox1_Leave(sender As Object, e As EventArgs) Handles ComboBox1.Leave
ComboBox1.Text = "Ruby"
End Sub
Private Sub ComboBox1_LocationChanged(sender As Object, e As EventArgs) Handles ComboBox1.LocationChanged
ComboBox1.Text = "Ruby"
End Sub
Since the user will choose, say print <<"EOF"; ---mytext---EOF from dropdown list and this will automatically print on textbox. He or she must go to textbox or somewhere else.
I know its not coventional to answer own question but if anyone needs help. Here it is

How to change selected item text in list box at run time?

I tried with code like this:
Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles MyBase.Leave
' This way is not working
ListBox1.SelectedItem = TextBox1.Text
' This is not working too
ListBox1.Items(ListBox1.SelectedIndex) = TextBox1.Text
End Sub
The form is looked like this:
I need to change that list text while user typing in the text box. Is it possible to do that at run time?
You are using the form's leave event MyBase.Leave, so when it fires, it is useless to you.
Try using the TextChanged event of the TextBox instead.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
Handles TextBox1.TextChanged
Make sure to check if an item is actually selected in the ListBox:
If ListBox1.SelectedIndex > -1 Then
ListBox1.Items(ListBox1.SelectedIndex) = TextBox1.Text
End If
Use Double click to select line (item) inside list box and change or modify.
Instead of using text box use ListBox1_MouseDoubleClick event
Private Sub ListBox1_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDoubleClick
then add this code inside this event
Dim intIndex As Integer = ListBox1.Items.IndexOf(ListBox1.SelectedItem)
Dim objInputBox As Object = InputBox("Change Item :","Edit", ListBox1.SelectedItem)
If Not objInputBox = Nothing Then
ListBox1.Items.Remove(ListBox1.SelectedItem)
ListBox1.Items.Insert(intIndex, objInputBox)
End If
OR
Dim objInputBox As Object = InputBox("Change Item :","Edit", ListBox1.SelectedItem)
If Not objInputBox = Nothing Then
ListBox1.Items(ListBox1.SelectedIndex) = objInputBox
End If