I am trying to rework asp.net usercontrol with .ascx markup to WebControl(only .cs).
In my_new_webcontrol.cs I have:
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);
}
Problem is that it generates DropDownList with id="MainContent_ComboBox1$Source"
and name="ctl00$MainContent$ComboBox1$Source"
. Name generated as expected but Id wrong and here should be _ instead of $.
How I can achieve id="MainContent_ComboBox1_Source"
and name="ctl00$MainContent$ComboBox1$Source"
.
Update 1.
Tried to put DropDownList into Panel as Knaģis suggested:
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);
}
No success. Generated HTML(ComboBox1 in id and name missing):
<div id="MainContent_ComboBox1">
<select name="ctl00$MainContent$Source" onchange="javascript:setTimeout('__doPostBack(\'ctl00$MainContent$Source\',\'\')', 0)" id="MainContent_Source"></select>
</div>
Answer
As Knaģis suggested I missed INamingContainer in my server control class declaration
public class ComboBox: WebControl, INamingContainer
You should add a child panel (or another container control) with ID of ComboBox1
and then within that add your DropDownList
with ID of Source
. Let the ASP.NET generate the hierarchical identifiers.
In short - if you want to preserve the values of ClientID
and Name
for your reworked control, you should use the exact same control tree as your .ascx
markup.