添加多个文本框.net

时间:2016-02-25 14:40:22

标签: vb.net ms-access

我想要的是当我在texbox1.text中输入一个数字时,例如我输入3它应该显示3个文本框但我总是得到一个错误。而且我必须将其保存在数据库中,但我不知道如何。请帮助..

Private boxes(TextBox1.text) As TextBox


Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim newbox As TextBox
    For i As Integer = 1 To TextBox1.Text
        newbox = New TextBox
        newbox.Size = New Drawing.Size(575, 35)
        newbox.Location = New Point(10, 10 + 35 * (i - 1))
        newbox.Name = "TextBox" & i
        newbox.Text = newbox.Name
        'connect it to a handler, save a reference to the array and add it to the form controls
        AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
        boxes(i) = newbox
        Me.Controls.Add(newbox)
    Next

End Sub

1 个答案:

答案 0 :(得分:3)

行。我尝试运行代码时遇到的错误是: -

An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

Additional information: Conversion from string "" to type 'Integer' is not valid.`

这是因为您尝试使用字符串作为循环的终止索引来启动循环。尝试使用

For i As Integer = 1 To Val(TextBox1.Text)

您的下一个问题将取决于您如何声明boxes。如果你已经宣布这样......

Dim boxes() As TextBox

你最终会得到一个Null引用异常,因为当你声明boxes时,你没有提供任何元素。要解决这个问题,你需要在循环之前添加它..

ReDim Preserve boxes(Val(TextBox1.Text))

如果boxes是一个列表..并且说实话..这是一个比数组更好的选择,而不是上面的行,你需要更改

boxes(i) = newbox

boxes.Add(newbox)

您可能还需要更改与boxes相关联的其他代码,但这项工作是值得的。

您最大的问题是,您正试图从尚未出现的TextBox中获取值。您已将代码放在表单的load事件中。它确实需要采用单独的方法。哦,而不是使用TextBox.changed事件,您应该使用按钮控件来执行该方法。否则,某人更容易更改文本框中的数字。使用您的代码,每次更改文本框(删除一个数字或添加另一个数字),将添加更多的TextBoxes,您可能最终会有很多。

所以可能的最终代码应该是......

Public Class Form1

    Dim boxes As New List(Of TextBox)

    Private Sub Addbuttons(buttonCount As Integer)
        Dim newbox As TextBox
        For i As Integer = 1 To buttonCount
            newbox = New TextBox
            newbox.Size = New Drawing.Size(575, 35)
            newbox.Location = New Drawing.Point(10, 10 + 35 * (i - 1))
            newbox.Name = "TextBox" & i
            newbox.Text = newbox.Name
            'connect it to a handler, save a reference to the array and add it to the form controls
            boxes.Add(newbox)
            Me.Controls.Add(newbox)
        Next
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Addbuttons(Val(TextBox1.Text))
    End Sub
End Class