Nez*_*ezz 0 c# variables loops
我只是想知道这一点,试图清理我的代码,以及将来的参考.
我有一些textBoxes.
tbPart1.Clear();
tbPart2.Clear();
tbPart3.Clear();
tbPart4.Clear();
tbPart5.Clear();
tbPart6.Clear();
tbPart7.Clear();
Run Code Online (Sandbox Code Playgroud)
有什么办法可以用循环代替数字吗?
我试过这个,但不知道我怎么能运行这个字符串.
for (int i = 1; i == 7; i++)
{
string p = "tbPart" + i.ToString() + ".Clear";
}
Run Code Online (Sandbox Code Playgroud)
在表单代码内部(即在按钮单击事件处理程序中),您可以枚举TextBox
表单上的所有控件并对它们执行特定操作:
this.Controls.OfType<TextBox>().ToList().ForEach(x => x.Clear());
Run Code Online (Sandbox Code Playgroud)
如果你只需要清除一些的的TextBox
控制,可以提供一种像这样过滤器:
this.Controls.OfType<TextBox>()
// Add a condition to clear only some of the text boxes - i.e. those named "tbPart..."
.Where(x=>x.Name.StartsWith("tbPart"))
.ToList().ForEach(x => x.Clear());
Run Code Online (Sandbox Code Playgroud)