|
-
Oct 16th, 2006, 07:47 AM
#1
Thread Starter
Fanatic Member
[02/03] Accessing controls dynamically
Hi,
Say I have 5 textboxes on my form (TextBox1, TextBox2, ...TextBox5).
Now I want to access them using their names:
Something like me.Controls("TextBox" & n.ToString).Text.
Is there any way out?
-
Oct 16th, 2006, 07:52 AM
#2
Hyperactive Member
Re: [02/03] Accessing controls dynamically
Check this code
VB Code:
Dim c As Control
For Each c In Me.Controls
If TypeOf c Is TextBox AndAlso CType(c, TextBox).Name = "textbox1" Then
'you find it just do whatever you want
CType(c, TextBox).Text = "anything"
End If
Next
Hope this helps
-
Oct 16th, 2006, 08:04 AM
#3
Thread Starter
Fanatic Member
Re: [02/03] Accessing controls dynamically
I need something like this
VB Code:
i = 0
Do While rdr.Read
me.controls("txtMyTextBox" & i.ToString).Text = "Some text"
i += 1
Loop
If TypeOf c Is TextBox AndAlso CType(c, TextBox).Name = "textbox1" Then
If I know the name of the textbox then I could have easily written it as me.TextBox1.
-
Oct 16th, 2006, 08:30 AM
#4
Hyperactive Member
Re: [02/03] Accessing controls dynamically
You have the name property on the controls collection, but there is no way to call an object like you are want, just a loop on all controls checking the name of the desired control once you get, do the action.
-
Oct 16th, 2006, 08:31 AM
#5
Re: [02/03] Accessing controls dynamically
Argh! It hurts me physically every time I see this question. Put you controls in an array and then access them by index:
VB Code:
Private textBoxes As TextBox()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.textBoxes = New TextBox() {Me.TextBox1, Me.TextBox2, Me.TextBox3, Me.TextBox4, Me.TextBox5}
End Sub
Private Sub PopulateTextBoxes()
For i As Integer = 0 To Me.textBoxes.GetUpperBound(0)
Me.textBoxes(i).Text = "TextBox" & (i + 1)
Next i
End Sub
-
Oct 16th, 2006, 09:09 AM
#6
Thread Starter
Fanatic Member
Re: [02/03] Accessing controls dynamically
This is really cool buddy. Sorry for hurting you. But I still miss VB 6 control arrays, wherein we easily assign index to them and use it accordingly.
Anyways....thx a tonne.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|