Panel.FindControl() 方法未找到已添加到其中的控件
考虑以下代码,添加 2 个具有相同 ID 的文本框 (哎呀):
protected void Page_Load(object sender, EventArgs e)
{
string TextBoxName = "TextBox1";
Panel p = new Panel();
TextBox t = new TextBox();
t.ID = TextBoxName;
p.Controls.Add(t);
if (p.FindControl(TextBoxName) == null) // <-------*******
{
TextBox t2 = new TextBox();
t2.ID = TextBoxName;
p.Controls.Add(t2);
}
Page.Form.Controls.Add(p);
}
该代码旨在停止添加相同 ID 两次。但是,Panel.FindControl()
方法未找到上一行代码中添加的控件。
我是否以错误的方式使用它?
我的意思是 - 当然 - 我可以手动迭代下一个级别的控件,例如:
string TextBoxName = "TextBox1";
Panel p = new Panel();
TextBox t = new TextBox();
t.ID = TextBoxName;
p.Controls.Add(t);
TextBox t2 = new TextBox();
t2.ID = TextBoxName;
bool duplicateFound = false;
foreach( Control c in p.Controls )
{
if(c.ID == TextBoxName)
{
duplicateFound = true;
break;
}
}
if( duplicateFound )
{
t2.ID = TextBoxName + "__0";
p.Controls.Add(t2);
}
但我不明白为什么这不起作用,而 Placeholder
控件和UserControl
工作正常。
我使用 Panel
的原因是为了 CSS 样式。身体>分区>输入 - 但仍然 - 它不起作用。
Consider the following code, adding 2 textboxes with the same ID (oops):
protected void Page_Load(object sender, EventArgs e)
{
string TextBoxName = "TextBox1";
Panel p = new Panel();
TextBox t = new TextBox();
t.ID = TextBoxName;
p.Controls.Add(t);
if (p.FindControl(TextBoxName) == null) // <-------*******
{
TextBox t2 = new TextBox();
t2.ID = TextBoxName;
p.Controls.Add(t2);
}
Page.Form.Controls.Add(p);
}
The code is designed to stop adding the same ID twice. However, the Panel.FindControl()
method is not finding a control that was added in the previous line of code.
Am I using this in the wrong way?
I mean - sure - I could manually iterate through the controls in the next level, like:
string TextBoxName = "TextBox1";
Panel p = new Panel();
TextBox t = new TextBox();
t.ID = TextBoxName;
p.Controls.Add(t);
TextBox t2 = new TextBox();
t2.ID = TextBoxName;
bool duplicateFound = false;
foreach( Control c in p.Controls )
{
if(c.ID == TextBoxName)
{
duplicateFound = true;
break;
}
}
if( duplicateFound )
{
t2.ID = TextBoxName + "__0";
p.Controls.Add(t2);
}
But I don't understand why this isn't working, whereas Placeholder
controls and UserControl
s work fine.
The reason I am using Panel
s is for CSS styling. body > div > input - but still - it isn't working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能是因为
Panel p
尚未添加到页面。首先尝试将其添加到页面,然后看看会发生什么。This could be because
Panel p
has not yet been added to the page. Try adding it to the page first, then see what happens.