vb.net 单击按钮时动态添加文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13515523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dynamically add textbox on button click
提问by Javed Salat
I'm working with windows form application in vb.net windows form application in that there are two buttons:
我在 vb.net windows 窗体应用程序中使用 windows 窗体应用程序,因为有两个按钮:
- Add new Textbox
- Insert multiple textbox data into database
- 添加新的文本框
- 将多个文本框数据插入数据库
When I click on 1st button it will create new textbox and if I click on 2nd button than it should insert data of multiple textboxes in database.
当我点击第一个按钮时,它会创建新的文本框,如果我点击第二个按钮,它应该在数据库中插入多个文本框的数据。
Database has two fields only
数据库只有两个字段
- Id primary key
- Name
- id 主键
- 姓名
And textbox contains name.
并且文本框包含名称。
Please suggest me the way to implement this i have no idea about this.
请建议我实现这一点的方法我对此一无所知。
回答by
In your click-event assuming the ID-field is auto-incrementing in the database:
在您的点击事件中,假设 ID 字段在数据库中自动递增:
dim myTxt as New TextBox
myTxt.Name = Me.Controls.Count.ToString '"random" name
myTxt.Location = New Point(10, 10) 'set the position according to your layout
myTxt.Tag = "For DB" 'something to identify it by
myTxt.Visible = True
Me.Controls.Add(myTxt) 'add it to form's control collection.
Me.Refresh 'If in panel etc. change Me with that control.
Then in your second click event:
然后在您的第二个点击事件中:
... open database, do checks etc.
For each c As Control in Me.Controls
If typeof c Is TextBox AndAlso c.Tag ="For DB" Then
Dim txt As String = CType(c, TextBox).Text
'insert txt into database
End If
Next
(A data-grid can do this for you as well).
(数据网格也可以为您做到这一点)。
Also you can use an array to perform the creation, and you can interact with each textbox you create by its index.
您也可以使用数组来执行创建,并且您可以通过其索引与您创建的每个文本框进行交互。
For y As UShort = 0 To indexsize_b - 1
For x As UShort = 0 To indexsize_a - 1
array(x, y) = New TextBox
array(x, y).Size = New Size(60, 20)
array(x, y).Location = New Point(5 + 60 * x, 40 + 20 * y)
array(x, y).Visible = True
Me.Controls.Add(array(x, y))
Next
Next
Interact via something like:
通过以下方式进行交互:
string s = array(a, b).text

