Rio Ablas
Rio Ablas

Reputation: 51

how to enumerate listbox?

Hi I'm new to Visual Studio and I am in need of a help in Visual Studio on a Windows Form App. also I don't really know if this is vb.net

I would like to make an application where if a user inputs something in the TextBox, it is presented in the ListBox whilst having some sort of an enumeration.

like for example.

If I type "Wow amazing" in the TextBox and confirm it. Then type another text like "I love you" in the TextBox and confirm it again

It should show up in the Listbox as "1. Wow Amazing" and "2. I love you".

Here's my code. I am not able to get it right and I don't really know how. I tried doing the for Loops and Do While but it would just duplicate the texts or am I doing something wrong?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer = 0
ListBox1.Items.Add(i + 1 & ". " & TextBox1.Text)
End Sub

Upvotes: 0

Views: 149

Answers (1)

Michał Turczyn
Michał Turczyn

Reputation: 37367

You are so close!

On every button click you need to:

  1. Take number of elements in list, to determine the number.

  2. Insert text concatenated with number.

So, you should use this code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'Step 1
    Dim i As Integer = ListBox1.Items.Count + 1
    'Step 2
    ListBox1.Items.Add(i & ". " & TextBox1.Text)
End Sub

Upvotes: 1

Related Questions