好,所以我进行了无数次搜索,并提供了以下代码来增加文本框的名称,但它不起作用。文本框位于选项卡控件中,这有关系吗?我试图在选项卡控件中引用它,但没有乐趣。
Public Cpv_Coeffs As New List(Of Decimal)
Dim i As Integer
For i = 0 To 6
'Cpv_Coeffs.Add(txt_Cp_Coef_A1.Text) 'this line works fine
Cpv_Coeffs.Add(Me.Controls("txt_Cp_Coef_A" & 1).Text)
Next i
我只是得到一个空引用异常 我要去哪里错了?
答案 0 :(得分:1)
如果您希望它正常工作,无论控件位于哪个容器中,请使用Controls.Find()功能。无论嵌套的深度如何,它都可以递归搜索该控件:
Public Cpv_Coeffs As New List(Of Decimal)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ctlName As String
For i As Integer = 0 To 6
ctlName = "txt_Cp_Coef_A" & i
Dim ctl As Control = Me.Controls.Find(ctlName, True).FirstOrDefault
If Not IsNothing(ctl) AndAlso TypeOf ctl Is TextBox Then
Dim tb As TextBox = DirectCast(ctl, TextBox)
Dim dcml As Decimal
If Decimal.TryParse(tb.Text, dcml) Then
Cpv_Coeffs.Add(dcml)
Else
MessageBox.Show("Value: " & tb.Text, "Invalid Decimal")
End If
Else
MessageBox.Show("Name: " & ctlName & vbCrLf & "Could Not Find Control, or it was not a TextBox.", "Error")
End If
Next i
End Sub
上面的示例很详细,但是它向您确切显示了所有故障点可能发生的位置。