1

I have 20+ text boxes that are all named like: TxtCustom1 TxtCustom2 TxtCustom3 and so on...

I want to be able to assign those text boxes values in a loop by building the text box var name dynamically with a int concatenated so that my loop would be something like this pseudo code:

For Each pair In Dictionary
TxtCustom{pair.key}.Text = pair.Value 
Next

Is building names dynamically like this possible in vb.net, how would something like this be accomplished?

1 Answer 1

2

Seems like it would be better to use some kind of control like a grid for this than a series of textboxes with names following a template, but here is how you do it based on the scenario you discussed.

For Each pair In Dictionary
   Me.Controls(String.format("TxtCustom{0}",pair.key)).Text= pair.Value 
Next
Sign up to request clarification or add additional context in comments.

3 Comments

Furthermore, for anything other than properties that exist on Control (such as .Text), you'd need to cast the return of Me.Controls() into that type: CType(Me.Controls("txtCustom" & pair.key), TextBox).PasswordChar = "*" , for example
Thanks for the help. Me.Controls(String.Format("TxtCustom{0}", pair.Key)).Text = pair.Value is giving me a "Object reference not set to an instance of an object" NullReferenceException, I know the key and values exist.
try replacing the string.format(...) part with a hardcoded string with the exact textbox control name to confirm that the object exists. I tested this code as is with a sample form and it worked fine for me. The only thing I can think is that the pair.key value isn't correct. or the control name doesn't start with "TxtCustom"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.