How to create a unique identifier for controls inside a user control

I have a User Control in which I have one label.

<asp:Label ID="lblProductionName" 
           runat="server" 
           Text="Production Name will come here">
</asp:Label>

I am processing a given UC from code using this function:

private string RenderControl(Control control)
{
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter writer = new HtmlTextWriter(sw);

    control.RenderControl(writer);
    return sb.ToString();
}

After rendering, I get this as the output string:

<span id="lblProductionName">Production Name will come here</span>

Now, when I put two instances of the same User Control, I get the same range identifier in the output string.

I want to create two different identifiers for two instances of User Control. How can I generate it?

+4
source share
2 answers

You can try something like this:

private Dictionary<string, int> controlInstances = new Dictionary<string, int>();

private string RenderControl(Control control)
{
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter writer = new HtmlTextWriter(sw);

    int index = GetOrAddControlInstanceCount(control);

    control.ClientIDMode = ClientIDMode.Static;
    control.ID = control.GetType().Name + index;

    control.RenderControl(writer);

    return sb.ToString();
}

private int GetOrAddControlInstanceCount(Control control)
{
    string key = control.GetType().Name;

    if (!controlInstances.ContainsKey(key))
    {
        controlInstances.Add(key, 0);
    }

    return controlInstances[key]++;
}

NamingContainer.

0

, , : Guid.NewGuid:)

0

All Articles