C# 动态添加的子控件的ClientID错误

C# 动态添加的子控件的ClientID错误,c#,user-controls,webforms,parent-child,web-controls,C#,User Controls,Webforms,Parent Child,Web Controls,我正在尝试将带有.ascx标记的asp.net usercontrol修改为WebControl(仅.cs) 在my_new_webcontrol.cs中,我有: private readonly DropDownList _source = new DropDownList(); protected override void OnInit(EventArgs e) { base.OnInit(e); _source.ID = String.Format("{0}{1}{2}

我正在尝试将带有.ascx标记的asp.net usercontrol修改为WebControl(仅.cs)

在my_new_webcontrol.cs中,我有:

private readonly DropDownList _source = new DropDownList();

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    _source.ID = String.Format("{0}{1}{2}", ID, IdSeparator, "Source");
    Controls.Add(_source);
}

protected override void Render(HtmlTextWriter writer)
{
    RenderContents(writer);
}

protected override void RenderContents(HtmlTextWriter writer)
{
    _source.RenderControl(writer);
}
问题是,它使用
id=“MainContent\u ComboBox1$Source”
name=“ctl00$MainContent$ComboBox1$Source”
生成DropDownList。名称按预期生成,但Id错误,此处应为\u而不是$

如何实现
id=“MainContent\u ComboBox1\u Source”
name=“ctl00$MainContent$ComboBox1$Source”

更新1。

试图将DropDownList放入面板,因为Knaģis建议:

private readonly DropDownList _source = new DropDownList();
private readonly Panel _panel = new Panel();

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    _panel.ID = ID;
    _panel.Controls.Add(_source);
    Controls.Add(_panel);
}

protected override void Render(HtmlTextWriter writer)
{
    RenderContents(writer);
}

protected override void RenderContents(HtmlTextWriter writer)
{
    _panel.RenderControl(writer);
}
没有成功。生成的HTML(id和名称中缺少ComboBox1):


您应该添加ID为
ComboBox1
的子面板(或另一个容器控件),然后在其中添加ID为
Source
DropDownList
。让ASP.NET生成层次标识符


简言之-如果您想为您的返工控件保留
ClientID
Name
的值,您应该使用与
.ascx
标记完全相同的控件树。

我不知道。“始终返回下划线字符(
)”。然后我将有d=“MainContent\u ComboBox1\u Source”和name=“ctl00$MainContent$ComboBox1\u Source”我没有考虑这一点,因为在原件.ASCX中,我在文件的根中生成正确ID和名称的选择,而没有父容器。ASP.NET自己生成ID吗?我按照您的建议尝试了面板,但没有成功(请参见更新1)。我甚至尝试手动将ClientIDMode设置为Predictable尝试创建这样的面板控件:
公共类ContainerPanel:panel,InAdminContainer{}
。噢,不。太蠢了=(有趣的是,我在周二通过的70-515考试中遇到了INamingContainer的问题=)Liels paldies,Knaģis。
<div id="MainContent_ComboBox1">
    <select name="ctl00$MainContent$Source" onchange="javascript:setTimeout('__doPostBack(\'ctl00$MainContent$Source\',\'\')', 0)" id="MainContent_Source"></select>    
</div>
public class ComboBox: WebControl, INamingContainer