0

我是 Visual Basic 的新手。我有一个像这样的小程序。 https://www.dropbox.com/s/xr44pxp3n79atkk/wall.png

它将通过将所有墙壁面积相加来计算总面积。

Public Sub btnWallAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWallAdd.Click
    FlowLayoutPanel1.Controls.Clear()
    FlowLayoutPanel1.AutoScroll = True

    For i As Integer = 1 To Val(txtWallNo.Text)
        Dim Width As New TextBox()
        Dim Height As New TextBox()

        Width.Name = "Width" & i
        Width.Text = Width.Name
        Height.Name = "Height" & i
        Height.Text = Height.Name

        FlowLayoutPanel1.Controls.Add(Width)
        FlowLayoutPanel1.Controls.Add(Height)

    Next
End Sub

我已经根据用户输入的数字成功创建了动态文本框,但我不知道如何从这些文本框中获取值并将它们相加。请教我怎么做。非常感谢你!对不起我的英语不好!

4

1 回答 1

1

您可以按名称访问控件,如下所示:

Dim txtWidth As TextBox = FlowLayoutPanel1.Controls.Item("Width" & i)

或者,如果您打开了选项 strict,您需要明确说明类型转换:

Dim txtWidth As TextBox = CType(FlowLayoutPanel1.Controls.Item("Width" & i.ToString()), TextBox)

例如,要将所有墙壁上的面积相加,您可以执行以下操作:

Public Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
    Dim totalArea As Decimal = 0
    For i As Integer = 1 To Val(txtWallNo.Text)
        Dim txtWidth As TextBox = CType(FlowLayoutPanel1.Controls.Item("Width" & i.ToString()), TextBox)
        Dim txtHeight As TextBox = CType(FlowLayoutPanel1.Controls.Item("Height" & i.ToString()), TextBox)
        totalArea = totalArea + (Decimal.Parse(txtHeight.Text) * Decimal.Parse(txtWidth.Text))
    Next
    lblResult.Text = totalArea.ToString()
End Sub
于 2012-08-06T12:09:48.630 回答