col*_*gem 6 c# asp.net code-behind
假设我的ID为"Input1","Input2"和"Input3".
有没有办法循环它们,而不是必须写:
Input1.Value = 1;
Input2.Value = 1;
Input3.Value = 1;
Run Code Online (Sandbox Code Playgroud)
在jquery中你可以只引用像$('#Input'+ i)这样的元素并循环遍历i,类似的东西在后面的ASP代码中非常有用.
编辑:呃,我再次搜索以查找页面上的所有“x”控件,并得出以下源代码:
foreach(Control c in Page.Controls)
{
if (c is TextBox)
{
// Do whatever you want to do with your textbox.
}
}
Run Code Online (Sandbox Code Playgroud)
有点......根据您的示例命名方案,您可以执行如下操作:
private void Button1_Click(object sender, EventArgs MyEventArgs)
{
string controlName = TextBox
for(int i=1;i<4;i++)
{
// Find control on page.
Control myControl1 = FindControl(controlName+i);
if(myControl1!=null)
{
// Get control's parent.
Control myControl2 = myControl1.Parent;
Response.Write("Parent of the text box is : " + myControl2.ID);
}
else
{
Response.Write("Control not found");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将允许您循环遍历以数字命名的控件,但否则它有点笨拙。