我已通过按钮点击声明了一个文本框:
Dim tp = TabControl2.TabPages(TabControl2.TabPages.Count - 1)
Dim txtbox As New TextBox()
txtbox.Location = New Point(200, 0)
txtbox.Height = 20
txtbox.Width = 100
tp.Controls.Add(txtbox)
现在我希望另一个子标签显示文本框的内容。我的第一次尝试是:
label.Text = txtbox.text
但这不起作用,因为我的文本框是在本地声明的,我不知道如何将其声明为全局变量......
答案 0 :(得分:3)
You should try to avoid global variables if there are workarounds for the task you have. For example you can retrieve your textbox from the Controls collection where you have added it. You just need something to help you locate the right textbox.
Dim tp = TabControl2.TabPages(TabControl2.TabPages.Count - 1)
Dim txtbox As New TextBox()
txtbox.Location = New Point(200, 0)
txtbox.Height = 20
txtbox.Width = 100
txtbox.Name = "MyImportantTextBox"
tp.Controls.Add(txtbox)
Now when you want to retrieve it
Dim tp = TabControl2.TabPages(TabControl2.TabPages.Count - 1)
Dim textbox = tp.Controls.
OfType(Of TextBox).
FirstOrDefault(Function(x) x.Name = "MyImportantTextBox")
if textbox IsNot Nothing Then
label.Text = textbox.Text
End If
There is also another simpler possibility, add an handler for the textbox TextChanged event and when you type something in that textbox reflect the content in the label.
Dim tp = TabControl2.TabPages(TabControl2.TabPages.Count - 1)
Dim txtbox As New TextBox()
txtbox.Location = New Point(200, 0)
txtbox.Height = 20
txtbox.Width = 100
AddHandler txtbox.TextChanged, AddressOf OnMyTextBoxChange
tp.Controls.Add(txtbox)
And add an event handler for the txtbox like this
Sub OnMyTextBoxChange(sender as Object, e as EventArgs)
Dim txtbox = DirectCast(sender, TextBox)
label.Text = txtbox.Text
End Sub
答案 1 :(得分:0)
问题是你从未设置text属性。试试这个:
Dim tp = TabControl2.TabPages(TabControl2.TabPages.Count - 1)
Dim txtbox As New TextBox()
txtbox.Text = "Some Text"
txtbox.Location = New Point(200, 0)
txtbox.Height = 20
txtbox.Width = 100
tp.Controls.Add(txtbox)
我在你的例子中添加了一行代码。
答案 2 :(得分:0)
Bryan had a good idea.
My personal choice would be declaring a global string variable and during your button click procedure assigning it the value of your textbox.