Syed Abdullah
Syed Abdullah

Reputation: 25

How to Print triangle in vb.net listbox

I am trying to print a triangle of 8 lines in a listbox control using vb.net. I have tried it many times but i am unable achieve it.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim i, j, n As Integer
    i = 1
    j = 1
    n = 8
    While i <= n
        i += 1
        j = 1
        While j <= 1
            listbox1.items.add( "*" & vbCrLf)
            j += 1
        End While

    End While

End Sub

Upvotes: 0

Views: 3901

Answers (1)

Mark Hall
Mark Hall

Reputation: 54532

I see 2 things right of the top of my head. In your second While statement you have J <=1 instead of J <= i. But the main thing is that you are not building a string for your "*" and then adding that to your ListBox, instead you are adding individual item's for each * .

Here is one way

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim i, j, n As Integer
    i = 1
    j = 1
    n = 8
    While i <= n
        j = 1
        Dim tmp As String = "" 'String to build your Line
        While j <= i
            tmp += "*"
            j += 1
        End While
        ListBox1.Items.Add(tmp)
        i += 1 'Moved to end otherwise you start with 2 *'s
    End While

End Sub

and another using just one While

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim i, n As Integer
    i = 1
    n = 8

    While i <= n
        ListBox1.Items.Add(StrDup(i, "*") )
        i += 1
    End While

End Sub

Upvotes: 1

Related Questions