2

In VB I can loop through controls, or refer to a control by concatenating a variable to a string. Something like:

Dim I as integer
I = 1
Me["Textbox" & I].Text = "Some text"

What is the C# equivalent of this last statement?

3
  • 2
    are you sure this line Me["Textbox" & I].Text = "Some text" works in VBNet? Commented Jan 29, 2013 at 8:56
  • Not sure about VB.net, but defintely normal VB and VBA. I assumed the behaviour will be carried over to VB.net Commented Jan 29, 2013 at 8:57
  • Why should he remove the C# tag? This is manifestly a question about how to do something in C#! Or he should at least add the WinForms tag. Commented Jan 29, 2013 at 8:58

4 Answers 4

6

You can access the control by the control's name:

Me.Controls("TextBox" & I).Text = "Some text"

And the same in C#:

this.Controls["TextBox" + I].Text = "Some text";
Sign up to request clarification or add additional context in comments.

1 Comment

C# does not have the Me collection. And replacing Me with this does not work either. No wait. Using the controls collection might work...
2
int i = 1;
this.Controls["TextBox" & i].Text = "Some text";

The above code is assuming that it is in a Control/Form.

6 Comments

This does not give any compile errors, but in runtime it gives an error that the control is null. In the immediate window it will say that this.Controls["MyControl1") have a value, but if I assign it to something the error is this.Controls["MyControl1"]' is null
Possible issues (1) a control named "TextBox1" is not defined (2) is not "IN" this control but a subcontrol (3) the control has been loaded yet.
1. It is defined as I can read and the value from this.MyControl if I don't use the variable. So I guess it is not in the Controls collection. Will search some more.
Its most likely inside of a Panel or something.
Yes, it is a subcontrol. It was on a tab control. Thanks for help!!
|
2

Close to SysDragan' solution, but Me just needs to be replaced with this. And yes, you need to specify the Controls collection.

this.Controls["TextBox" & I].Text = "Some text";

Comments

2
 int I = 1;
 this["Textbox" + I].Text = "some text";

OR

 int I = 1;
 this.Page["Textbox" + I].Text = "some text";

OR

 int I = 1;
 this.Controls["Textbox" + I].Text = "some text";

1 Comment

Seems like this is not working. Need to specify the Controls collection.

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.