vb.net 相当于通过变量名来引用控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14578957/
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
Equivalent to refer to control by variable name?
提问by Cameron Castillo
In VB I can loop through controls, or refer to a control by concatenating a variable to a string. Something like:
在 VB 中,我可以循环访问控件,或者通过将变量连接到字符串来引用控件。就像是:
Dim I as integer
I = 1
Me["Textbox" & I].Text = "Some text"
What is the C# equivalent of this last statement?
最后一条语句的 C# 等效项是什么?
回答by SysDragon
You can access the control by the control's name:
您可以通过控件的名称访问控件:
Me.Controls("TextBox" & I).Text = "Some text"
And the same in C#:
在 C# 中也是如此:
this.Controls["TextBox" + I].Text = "Some text";
回答by Abdulrahman_88
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";
回答by Cameron Castillo
Close to SysDragan' solution, but Me just needs to be replaced with this. And yes, you need to specify the Controls collection.
接近 SysDragan 的解决方案,但我只需要用这个代替。是的,您需要指定 Controls 集合。
this.Controls["TextBox" & I].Text = "Some text";
回答by Richard Schneider
int i = 1;
this.Controls["TextBox" & i].Text = "Some text";
The above code is assuming that it is in a Control/Form.
上面的代码假设它在一个控件/窗体中。

