我是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
我已根据用户输入的数字成功创建了动态文本框,但我不知道如何从这些文本框中获取值并添加它们。请教我怎么做。非常感谢你! 抱歉我的英文!
答案 0 :(得分:1)
您可以按名称访问控件,如下所示:
Dim txtWidth As TextBox = FlowLayoutPanel1.Controls.Item("Width" & i)
或者,如果您启用了选项严格,则需要明确说明类型转换:
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