How to transfer data from listbox to textbox in Visual Basic - vb.net

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

Related

Converting check List in VB.NET to integer

This is my first time working with VB.Net It's a college assignment and is already due for submission.I want to create a simple program that determines if a user has Ebola or not. So, there is a list of checkbox containing the core symptoms of Ebola. If the user selects 4 or more there should be a prompt message saying the user most likely has Ebola otherwise user does not have Ebola.
I have created the form and it works but don't know how to implement the checkbox into numbers that will be summed up.
Here is the code for the form
Public Class Checkbxvb
Private Sub Checkbxvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = "Click to select the symptoms you are having"
CheckBox1.Text = "Fever"
CheckBox2.Text = "Loss of appetite"
CheckBox3.Text = "sore throat"
CheckBox4.Text = "Gastrointestinal Symptoms"
CheckBox5.Text = "Unexplained bleeding or bruising"
CheckBox6.Text = "Loss of weight"
Button1.Text = "Submit"
Button2.Text = "Close"
End Sub
I want to create a button that will collect the user input like I said earlier on. Thanks
If you are using a CheckListBox you can used its CheckedItems collection Count property to get what you need.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If CheckedListBox1.CheckedItems.Count > 3 Then
MessageBox.Show("You may have Ebola.")
Else
MessageBox.Show("You probably don't have Ebola.")
End If
End Sub
If you are using CheckBox controls add them to a List(Of T). The T stands for Type. Create a variable for the list at Form level so it can be seen from the Form.Load and the button click. Then you can loop through your collection and increment a counter when the Checked property is True.
Private CkBxList As New List(Of CheckBox)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CkBxList.AddRange({CheckBox1, CheckBox2, CheckBox3, CheckBox4})
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim counter As Integer
For Each cb In CkBxList
If cb.Checked Then
counter += 1
End If
Next
If counter > 3 Then
MessageBox.Show("You may have Ebola.")
Else
MessageBox.Show("You probably don't have Ebola.")
End If
End Sub
As you can see the code is much simpler with a CheckedListBox. Try to use the control that best suits your purpose.

Having trouble with a lottery software

sorry to come in here like this looking for answers, but im actually really stumped. Im supposed to make an application using 2 forms, one to generate its own array and store user entered numbers into another array, and then display them on the second form and tell you how many of the numbers are in common
I cant get the numbers to show up on the second form at all, and I also cant really understand how to get how many numbers are matching, but I will when I can reference them properly in form 2. I got the arrays set up perfectly, but I cant even call the numbers from them to form 2. I need help calling the arrays from the first form to display on the next
Form 1 code
Public Class Form1
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Shared random As New Random()
Dim UserArray(4) As String
Dim LotteryArray(4) As String
Public Sub btnCheck_Click(sender As Object, e As EventArgs) Handles btnCheck.Click
If txtNumbers.Text <> "" Then
For i As Integer = 0 To 4
If UserArray(i) = "" Then
UserArray(i) = txtNumbers.Text
End If
Next
End If
For n As Integer = 0 To 9
Dim RandomNumber As Integer = CInt(Int(Rnd() * 5) + 1)
LotteryArray(4) = CStr(RandomNumber)
Next
End Sub
End Class
Form 2 Code
Public Class Form2
Public Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click
lblUser1.Text = Form1.UserArray(0)
lblUser2.Text = Form1.UserArray(1)
lblUser3.Text = Form1.UserArray(2)
lblUser4.Text = Form1.UserArray(3)
lblUser5.Text = Form1.UserArray(4)
lblRand1.Text = Form1.LotteryArray(0)
lblRand2.Text = Form1.LotteryArray(1)
lblRand3.Text = Form1.LotteryArray(2)
lblRand4.Text = Form1.LotteryArray(3)
lblRand5.Text = Form1.LotteryArray(4)
If Form1.LotteryArray(4) = Form1.UserArray(4) Then
MessageBox("CONGRATULATIONS!", "You Are The GRAND PRIZE WINNER!")
End If
Me.Close()
End Sub
End Class
I will address your first question. How to get your numbers into your second form.
You main problem is the Access modifier you used for your arrays. Dim is the equivalent of Private which means that the variable is only visible within the class. Friend is visible anywhere in the assembly. See https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/declared-elements/access-levels for more information. Don't change your event procedure Access to Public.
You have to let the user fill in another guess. The first loop in the Check button will only enter the same input 5 times. You need one entry on every click but you need to keep track of where you are in the array. Private NumberOfGuesses As Integer Note that this variable is Private. It doesn't need to be seen outside of the Form1 class.
We don't need to refill the LotteryArray on every click so I did it once in the Form.Load You were trying to use the Random class the way you use the old vb6 Random. The .net class is much easier.
To display the arrays on Form2, I used list boxes and loops. Saved a bit of typing.
If you still have a question about part 2 of your problem post another question. Show what you have tried.
Public Class Form1
Private random As New Random()
Friend UserArray(4) As Integer
Friend LotteryArray(9) As Integer
Private NumberOfGuesses As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For n As Integer = 0 To 9
Dim RandomNumber As Integer = random.Next(0, 10)
LotteryArray(n) = RandomNumber
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If NumberOfGuesses > 4 Then
MessageBox.Show("You have used up your guesses")
Form2.Show()
Me.Close()
End If
If TextBox1.Text <> "" Then
UserArray(NumberOfGuesses) = CInt(TextBox1.Text)
NumberOfGuesses += 1
TextBox1.Clear()
TextBox1.Focus()
End If
End Sub
End Class
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each number In Form1.UserArray
ListBox1.Items.Add(number)
Next
For Each number In Form1.LotteryArray
ListBox2.Items.Add(number)
Next
End Sub
End Class

How to Remove Duplicate Numbers all at once in a list box in Visual Basic

Public Class Form1
Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
ListBox1.Items.Add(0)
End Sub
Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
ListBox1.Items.Clear()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Add(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
ListBox1.Items.Add(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
ListBox1.Items.Add(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
ListBox1.Items.Add(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
ListBox1.Items.Add(5)
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
ListBox1.Items.Add(6)
End Sub
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
ListBox1.Items.Add(7)
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
ListBox1.Items.Add(8)
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
ListBox1.Items.Add(9)
End Sub
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
Dim intNumRemoved As Integer 'The number to be removed
Dim strInput As String 'To hold user input
strInput = InputBox("Enter the item that you want to remove") 'prompt the user to enter the item to be removed
If Integer.TryParse(strInput, intNumRemoved) Then 'Converting the user input from InputBox to an Integer
ListBox1.Items.Remove(intNumRemoved)
End If
End Sub
End Class
1.The user is allowed to add digits 0,1,2,3,4,5,6,7,8,9 to a listbox using buttons.
2.The user is allowed to "clear" the list box with a button.
3.When the user clicks on the "Remove Item" button, the program will:
a.Allow the user to input the name of an item in an InputBox
b.Remove all instances of items from the listbox even the duplicate ones
)
I know this is an older question, but maybe it will still help..
To remove all the numbers in your listbox you need to loop through each item and check if it is equal to the value inputted.
One thing to remember of course is that most things like ListBoxes,Lists,Arrays etc have zero-based indexes - means the first element starts at index 0)
Take a look at the list below - the left hand column is the position(index) in the list of the number, and the right hand column is the number itself.
0 4
1 9
2 5
3 1
4 4
5 7
6 3
7 3
8 6
9 2
10 8
Also, because of the way VB does loops, you need to go backwards. I'll try to explain ..
Below is code for the simplest loop
For i As Integer = 0 To 10
Next
When the loop first starts, the start point and end point of the loop are set in that first statement. They will never change. Look at this example
Dim loopStart As Integer = 0
Dim loopEnd As Integer = 10
For i As Integer = loopStart To loopEnd
Next
Pretty straight forward and works the same way as the first example.
However, if for some reason you change loopEnd in the loop like this ..
Dim loopStart As Integer = 0
Dim loopEnd As Integer = 10
For i As Integer = loopStart To loopEnd
loopEnd = 90000000
Next
The loop will still only execute 11 times. This is because the parameters of the actual loop are set the first time. This creates a small problem when you're removing items from a list
In the list of items above, we have 11 items. So the .Count of the items = 11. Because the index number of the last item is 10, we will need to tell the loop that the end point is ListBox1.Items.Count - 1 No problem.
So we go through the loop, find a matching number and remove it. Now we have a problem. When we remove an item, all the items further down the list are shuffled up to the next index.
E.G If we remove the number at index 5, the number that was at index six will now be at index 5, the number that was at index 7 will now be at index 6 and so on.
And now that an item has been removed, the count of the number of items will now be 10 and the last item will be at index 9. Because the end point of the loop is still 10 we will get an error when the program tries to access item 10. It doesn't exist.
The way to solve this is to go backwards through the loop.
Dim loopStart As Integer = 0
Dim loopEnd As Integer = Listbox1.Items.Count
For i As Integer = loopEnd To loopStart Step -1
Next
If we start at index 10, and go on to 9 and so on, if we get to item 5 and remove it, all the items further down the list will be shuffled up one. The next time the loop goes round, we will be at item 4 then 3 then 2 then 1 then 0. Because the end point of the loop is 0 and the item at index 0 still exists, the loop completes successfully and no problem.
So, the final code with your If .. Then statement will look like this ..
If Integer.TryParse(strInput, intNumRemoved) Then 'Converting the user input from InputBox to an Integer
For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1
If intNumRemoved = CInt(ListBox1.Items(i)) Then
ListBox1.Items.RemoveAt(i)
End If
Next
End If
Hope this helps.
By the way. My comment in your other question about not using controls as your primary way of storing data applies here as well. Instead of using a ListBox, you should store all your items in a List(Of integer) and work on that, then clear the Listbox and add the items from the List.

Moving average method VB

i'd try to make moving average in vb
i want to check the cells and set the value to text box
but the result is all the text box has the same value
how to make my first check value (penjualan/bulan) is inputed into first text box and the second check (penjualan/bulan) to second text box.
here is my code
Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
If e.ColumnIndex = 5 Then
tb1.Text = DataGridView1.CurrentRow.Cells(3).Value
tb2.Text = DataGridView1.CurrentRow.Cells(3).Value
tb3.Text = DataGridView1.CurrentRow.Cells(3).Value
End If
End Sub
thanks.
You set EVERY time the cellClicked-event is raised all 3 Textboxes to the same value, CurrentRow.Cells(3).Value.
Another problem is that your code will set the text in the Textboxes always. It dont check if the Checkbox is checked or not. it just updated every time you click in any cell in this column, the text in the 3 boxes to the value of your currently selected row.
Here you have a solution. Its not perfect but should work, although you should try to understand and optimize it.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitializeDgv()
End Sub
Private Sub InitializeDgv ()
Dim row as String() = New String(){"2016",240}
DataGridView1.Rows.Add(row)
row = New String(){"2017",223}
DataGridView1.Rows.Add(row)
row = New String(){"2015",54}
DataGridView1.Rows.Add(row)
End Sub
Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
if e.ColumnIndex=2
Dim checkedRows=(From dgv as DataGridViewRow in DataGridView1.Rows where dgv.Cells(2).Value=True select dgv).ToList()
Dim controlsList As new List(of TextBox)
controlsList.Add(TextBox1)
controlsList.Add(TextBox2)
controlsList.Add(TextBox3)
for Each item in controlsList
item.Text=String.Empty
Next
for i=0 to checkedRows.Count-1
controlsList(i).Text=checkedRows.Item(i).Cells(0).Value
Next
End If
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