如何在vb.net列表框中打印三角形

时间:2012-11-11 06:30:37

标签: vb.net

我正在尝试使用vb.net在列表框控件中打印8行的三角形。我已经多次尝试但我无法实现它。

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

1 个答案:

答案 0 :(得分:1)

我看到了我头顶的两件事。在您的第二个While声明中,您有J <=1而不是J <= i。但主要的是你没有为你的“*”构建字符串,然后将其添加到ListBox,而是为每个*添加单独的项目。

这是一种方式

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

和另一个只使用一个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