determine user control parameter at runtime
I hav开发者_StackOverflow社区e a user control which I call like this:
<MyNamespace:MyControl runAt="server" ID="foo" />
Is there any way I can determine the ID parameter at run-time and pass it in?
This is pretty straightforward; so long as it's constructed properly (using LoadControl for UserControls, for instance) and early enough for life-cycle initialization, you can assign the ID at will and retrieve the control using FindControl on the appropriate NamingContainer.
Here's a basic sample:
protected override void CreateChildControls()
{
for (int i = 0; i < 5; i++)
Controls.Add(new Literal() { ID = "MyControl" + i, Text = i.ToString() });
base.CreateChildControls();
}
protected override void OnPreRender(EventArgs e)
{
for (int i = 0; i < 5; i++)
Response.Write(((Literal)FindControl("MyControl" + i)).Text + "<br/>");
}
...that outputs:
0
1
2
3
4
01234
IF you want to do this programatically, then add the control dynamically in code behind.
The best strategy I've found is to set the control's OnInit callback, and use the codebehind to set the property value.
Of course, if you're in a template context, that's a different story.
Edit
Sorry, I read too quickly and didn't realize that you're trying to set the ID property itself. The point of the ID property is to uniquely identify this particular instance of the control, within the context of its parent control. Whatever you're trying to accomplish by setting this ID to some custom value is probably better accomplished using another strategy. Can you provide more information about the bigger problem that you're trying to solve?
Here's a technique that works even in a loop!
<script runat="server">
void AddTextBox(int i)
{
var ctrl = new TextBox() { ID = i.ToString()};
ctrl.RenderControl(new HtmlTextWriter(Response.Output));
}
</script>
<%
for (var i = 0; i < 5; i++)
{
%>
Control Rendering Begin
<br />
<%
AddTextBox(i);
%>
<br />
Control Rendering Ends
<br />
<%
}
%>
For what it's worth, here's the solution I ended up using:
<% Dim ctrlName As String %>
....
<% ctrlId = "whatever" 'need to wait until here to figure out the ID %>
....
<% mySpan.Controls.Add(New MyNamespace.MyControl() _
With { .ID = ctrlId }) %>
<span runat="server" id="mySpan" />
EDIT:
This won't work in a loop... see my better answer that works even in a loop.
精彩评论